Go gotcha: Can't change entries in range loop

Why isn’t the slice updated in this example?

s := []int{1, 1, 1}
for _, n := range s {
	n += 1
}
fmt.Println(s)
// Output: [1 1 1]
Answer

The range loop copies the values from the slice to a local variable n; updating n will not affect the slice.

Update the slice entries like this:

s := []int{1, 1, 1}
for i := range s {
	s[i] += 1
}
fmt.Println(s)
// Output: [2 2 2]

See Range loops (for each loops) explained for all about range loops in Go.

Comments

Be the first to comment!