Go - Passing arrays to functions


Advertisements

If you want to pass a single-dimension array as an argument in a function, you would have to declare function formal parameter in one of following two ways and all two declaration methods produce similar results because each tells the compiler that an integer array is going to be received. Similar way you can pass multi-dimensional array as formal parameters.

Way-1

Formal parameters as a sized array as follows −

void myFunction(param [10]int)
{
.
.
.
}

Way-2

Formal parameters as an unsized array as follows −

void myFunction(param []int)
{
.
.
.
}

Example

Now, consider the following function, which will take an array as an argument along with another argument and based on the passed arguments, it will return average of the numbers passed through the array as follows −

func getAverage(arr []int, int size) float32 {
   var i int
   var avg, sum float32  

   for i = 0; i < size; ++i {
      sum += arr[i]
   }

   avg = sum / size
   return avg;
}

Now, let us call the above function as follows −

package main

import "fmt"

func main() {
   /* an int array with 5 elements */
   var  balance = []int {1000, 2, 3, 17, 50}
   var avg float32

   /* pass array as an argument */
   avg = getAverage( balance, 5 ) ;

   /* output the returned value */
   fmt.Printf( "Average value is: %f ", avg );
}
func getAverage(arr []int, size int) float32 {
   var i,sum int
   var avg float32  

   for i = 0; i < size;i++ {
      sum += arr[i]
   }

   avg = float32(sum / size)
   return avg;
}

When the above code is compiled together and executed, it produces the following result −

Average value is: 214.400000

As you can see, the length of the array doesn't matter as far as the function is concerned because Go performs no bounds checking for formal parameters.

go_arrays.htm
Advertisements