DEV Community

nabbisen
nabbisen

Posted on β€’ Edited on

6 2 1 1

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)

πŸ‘‹ Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay