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]
The result is not [2 3 4] 😅
This is because each entry which range returns is:
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]
This post is based on my tweets:
Top comments (0)