Can’t change entries in range loop

yourbasic.org/golang

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 4 basic range loop (for-each) patterns for all about range loops in Go.

Share this page: