How to Pass Array to Function in Go: Syntax and Examples
func f(arr [3]int). The function receives a copy of the array, so changes inside the function do not affect the original array unless you pass a pointer.Syntax
To pass an array to a function in Go, declare the function parameter with the array type and its fixed size. For example, func f(arr [3]int) means the function f accepts an array of exactly 3 integers.
The array is passed by value, so the function gets a copy. To modify the original array, pass a pointer like *[3]int.
package main import "fmt" func example(arr [3]int) { // arr is a copy of the original array arr[0] = 100 } func main() { a := [3]int{1, 2, 3} example(a) fmt.Println(a) // prints [1 2 3], original array unchanged }
Example
This example shows passing an array to a function and printing its elements. It also shows that changes inside the function do not affect the original array.
package main import "fmt" func printArray(arr [3]int) { for i, v := range arr { fmt.Printf("Element %d: %d\n", i, v) } arr[0] = 100 // change inside function } func main() { myArray := [3]int{10, 20, 30} printArray(myArray) fmt.Println("After function call:", myArray) }
Common Pitfalls
Passing by value: Arrays are copied when passed to functions, so changes inside the function do not affect the original array.
Array size mismatch: The function parameter array size must exactly match the argument array size, or the code will not compile.
To modify the original array: Pass a pointer to the array instead of the array itself.
package main import "fmt" // Wrong: size mismatch causes compile error // func wrong(arr [2]int) {} // Correct: matching size func correct(arr [3]int) { arr[0] = 50 } // To modify original array, use pointer func modify(arr *[3]int) { arr[0] = 50 } func main() { a := [3]int{1, 2, 3} correct(a) fmt.Println("After correct call:", a) // unchanged modify(&a) fmt.Println("After modify call:", a) // changed }
Quick Reference
| Concept | Syntax Example | Notes |
|---|---|---|
| Pass array by value | func f(arr [3]int) | Function gets a copy; original unchanged |
| Pass pointer to array | func f(arr *[3]int) | Function can modify original array |
| Array size must match | func f(arr [3]int) | Array size in parameter must equal argument size |
| Call with pointer | f(&myArray) | Pass address to modify original |