Go gotcha: Why doesn't this function change my array?

func Foo(a [2]int) {
        a[0] = 8
}

func main() {
        a := [2]int{1, 2}
        Foo(a)         // Try to change 'a'
        fmt.Println(a) // Output: [1 2]
        
}
Answer
  • Arrays in Go are values.
  • When you pass an array to a function, the array is copied.
If you want Foo to update the elements of its argument a, use a slice instead:
func Foo(a []int) {
        if len(a) > 0 {
                a[0] = 8
        }
}

func main() {
        a := []int{1, 2}
        Foo(a)         // Change 'a'
        fmt.Println(a) // Output: [8 2]
}
A slice does not store any data, it just describes a section of an underlying array. Changing the elements of a slice modifies the corresponding elements of its underlying array. Other slices that share the same underlying array will see those changes. A Tour of Go: Slices
See Slices explained for all about slices in Go.

Comments (1)

User avatar

Or you can use a pointer to the array, as in

func Foo(a *[2]int) { a[0] = 8 }

by Krish |  Reply

Add comment