DEV Community

nabbisen
nabbisen

Posted on • Updated on

Go range loop: Failed to change value of entry

I found my misunderstanding on Go the other day.

arr := []int{1, 2, 3}
for _, entry := range arr {
    entry += 1
}
fmt.Printf("%v", arr)
// [1 2 3]
Enter fullscreen mode Exit fullscreen mode

The result is not [2 3 4] 😅

This is because each entry which range returns is:

a copy of the element at that index

In order to change value of element in array, use basic for loop with index 🙂

arr := []int{1, 2, 3}
for i := 0; i < len(arr); i++ {
    arr[i] += 1
}
fmt.Printf("%v", arr)
// [2 3 4]
Enter fullscreen mode Exit fullscreen mode

This post is based on my tweets:

Top comments (0)