Latest web development tutorials

Go language Passing arrays to functions

Go language array Go language array

If you want to pass an array of arguments to a function, you need a function definition, declare the parameter as an array, we can declare the following two ways:

One way

Parameter setting array size:

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

Second way

Parameter is not set array size:

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

Examples

Let's look at the following examples, examples function receives an integer array parameter, another parameter specifies the number of array elements and returns the average:

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;
}

Next we call the function:

package main

import "fmt"

func main() {
   /* 数组长度为 5 */
   var  balance = []int {1000, 2, 3, 17, 50}
   var avg float32

   /* 数组作为参数传递给函数 */
   avg = getAverage( balance, 5 ) ;

   /* 输出返回的平均值 */
   fmt.Printf( "平均值为: %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;
}

Examples of the implementation of the above output is:

平均值为: 214.000000

We use the example above shape parameter and the set array size.

Go language array Go language array