If you would like to access v's reference value (as in for i, v := range arr
) to update the value of the object in the array, there are three promising (relatively simple) workarounds:
Like the first answer suggested, update arr[i] instead of v from within the array (e.g., arr[i] = "Hello"
)
ONLY IF your array contains a set of structs you need to update but not replace in the array's assignment, set v to arr[i] within your array and then update properties through v (e.g., v := arr[i]; v.thingSheSays = "Hello";
)
Or, my favorite—define an array containing the object addresses. Then access the objects using a pointer from within the for-loop. Do this like so:
Input:
a, b, c := "A", "B", "C"
arr := []*string{&a, &b, &c}
fmt.Println("- Arr Value Updates:")
for i, v := range arr {
*v = "Hello"
fmt.Println("v's value: " + *v)
fmt.Println("arr[i]'s value: " + *arr[i])
}
Output:
- Arr Value Updates:
v's value: Hello
arr[i]'s value: Hello
v's value: Hello
arr[i]'s value: Hello
v's value: Hello
arr[i]'s value: Hello
Hope this was able to help someone, as it initially stumped me as a newbie to golang for-loops. Feel free to share your own methods for avoiding this issue!