Pass arrays to functions
Pass arrays to functions
An array parameter has a specific length and element type. Go passes arguments by value, so changing integer elements of an array parameter does not change the original. Return an updated array when the caller should decide whether to retain it.
package main
import "fmt"
func doubled(a [3]int) [3]int { for i := range a { a[i] *= 2 } return a}func main() { a := [3]int{1, 2, 3} b := doubled(a) fmt.Println(a, b)}The parameter a is a separate array value. The return value becomes b. The function accepts [3]int, not [2]int directly. This models a contract with a meaningful fixed length.
Expected output:
[1 2 3] [2 4 6]Use a pointer to modify the original
package main
import "fmt"
func reset(a *[3]int) { a[0] = 0 }func main() { a := [3]int{7, 8, 9} reset(&a) fmt.Println(a)}&a obtains the address of a. A *[3]int parameter receives a copy of the pointer, not a copy of the array. Indexing the pointer directly means indexing the pointed-to array. Never access elements through a nil array pointer. Pointers are covered later; slices handle variable lengths in the next chapter.
Expected output:
[0 8 9]Try it locally
Write sum(a [3]int) int returning the total with range. Print results for [3]int{3,4,5} and [3]int{}.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Arrays 07: Pass arrays to functions
Check the lesson objective before moving on.
Does changing an integer array parameter modify the original array?
What does a *[3]int parameter allow?