WEB DEVELOPER SITE

# Go passes array to function

If you want to pass array parameters to a function, you need to declare the formal parameter as an array when the function is defined. We can declare it in two ways:

### Method 1

Formal parameter setting array size:

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

### Method 2

Form parameter does not set the array size:

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

### Instance

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

## example

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

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

avg = sum / size

return avg;
}

Next we will call this function:

## example

package main

import "fmt"

func main() {
/* The length of the array is 5 */
var  balance = [5]int {1000, 2, 3, 17, 50}
var avg float32

/* Array passed as a parameter to the function */
avg = getAverage( balance, 5 ) ;

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

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

avg = float32(sum) / float32(size)

return avg;
}

The above example execution output is:

`The average is: 214.399994 `

The formal parameters we used in the above example did not set the array size.

The floating point calculation output has a certain deviation, you can also adjust the precision to set the precision.

## example

package main
import (
"fmt"
)
func main() {
a := 1.69
b := 1.7
c := a * b      // The result should be 2.873
fmt.Println(c)  // The output is2.8729999999999998
}

Set fixed accuracy:

## example

package main
import (
"fmt"
)
func main() {
a := 1690           // Indicates 1.69
b := 1700           // Indicates 1.70
c := a * b          // The result should be 2873000 2.873
fmt.Println(c)      // Internal coding
fmt.Println(float64(c) / 1000000) // display
}