Passing Arrays to Functions in Go

Go Arrays

In Go, arrays are value types, so when an array is passed to a function, a copy of the array is actually passed.

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

Method 1

Specifying the array size in the formal parameters:

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

Method 2

Not specifying the array size in the formal parameters:

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

If you want to modify the original array inside a function, you can do so by passing a pointer to the array.

Example

Let's look at the following example. In this example, the function receives an integer array parameter, another parameter specifies the number of elements in the array, and it returns the average value:

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, let's call this function:

Example

package main

import "fmt"

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

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

   /* Output the returned average */
   fmt.Printf( "Average value: %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 output result of the above example is:

平均值为: 214.399994

In the above example, the formal parameters we used did not specify the array size.

Floating-point calculations may have some deviation in output; you can also convert to an integer type to set 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 is 2.8729999999999998
}

Set fixed precision:

Example

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

If you want to modify the original array inside a function, you can do so by passing a pointer to the array.

The following example demonstrates how to pass an array to a function. The function accepts an array and a pointer to the array as parameters:

Example

package main

import "fmt"

// The function accepts an array as a parameter.
func modifyArray(arr [5]int) {
    for i := 0; i < len(arr); i++ {
        arr[i] = arr[i] * 2
    }
}

// The function accepts a pointer to an array as a parameter.
func modifyArrayWithPointer(arr *[5]int) {
    for i := 0; i < len(*arr); i++ {
        (*arr)[i] = (*arr)[i] * 2
    }
}

func main() {
    // Create an integer array containing 5 elements.
    myArray := [5]int{1, 2, 3, 4, 5}

    fmt.Println("Original Array:", myArray)

    // Passing an array to a function does not modify the value of the original array.
    modifyArray(myArray)
    fmt.Println("Array after modifyArray:", myArray)

    // Passing a pointer to an array to a function can modify the value of the original array.
    modifyArrayWithPointer(&myArray)
    fmt.Println("Array after modifyArrayWithPointer:", myArray)
}

In the above example, the modifyArray function accepts an array and attempts to modify the values of the array, but after calling it in the main function, the original array was not modified. In contrast, the modifyArrayWithPointer function accepts a pointer to the array and modifies the values of the original array through the pointer.

The output result of the above example is:

Original Array: [1 2 3 4 5]
Array after modifyArray: [1 2 3 4 5]
Array after modifyArrayWithPointer: [2 4 6 8 10]

Go Arrays

other extensions