How to pass an Array to a Function in Golang ?

To pass an array to a function in Go, you simply need to include the array as a parameter in the function’s signature. The function will receive a copy of the array, and any modifications made to the array within the function will not affect the original array outside of the function.

Here’s how you can pass an array to a function in Go:

package main

import "fmt"

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

func main() {
    // Declare and initialize an array
    numbers := [5]int{10, 20, 30, 40, 50}

    // Call the function and pass the array
    modifyArray(numbers)

    // Printing the modified array (no change will be reflected)
    fmt.Println("Modified array:", numbers)
}

Output :

Modified array: [10 20 30 40 50]

In the example above, the function modifyArray takes an array as a parameter. However, the modifications made to the array within the function don’t affect the original array outside of the function. This is because arrays in Go are passed by value, meaning that a copy of the array is created when passed to the function.

If you need to modify the original array within a function, you should pass a pointer to the array using a slice. Slices are more commonly used for dynamic collections of elements and provide more flexibility when dealing with arrays of varying sizes.