Home >Backend Development >Golang >Why Doesn't Modifying Values in Go's Range Loop Change the Original Array?
Range References Instead Values
In Go, the range keyword iterates over a sequence, such as an array or a slice, and provides access to both the key (index) and the value of each element. However, for performance reasons, the range keyword operates on a copy of the original value. This means that any modifications made to the value returned by range will not be reflected in the original array.
Example
Consider the following code:
package main import "fmt" type MyType struct { field string } func main() { var array [10]MyType // Attempting to modify a value returned by range for _, e := range array { e.field = "foo" } // Printing the values after the range loop for _, e := range array { fmt.Println(e.field) fmt.Println("--") } }
Running this code will print "000000" for all elements because the modifications made to e.field inside the first range loop are applied to a copy and do not affect the original value in the array.
Solution
To modify the values of an array using a range loop, you need to use the array index instead of the value returned by range. This can be achieved by capturing the index using the _ placeholder in the range loop.
package main import "fmt" type MyType struct { field string } func main() { var array [10]MyType // Using the array index to modify values for idx, _ := range array { array[idx].field = "foo" } // Printing the values after the range loop for _, e := range array { fmt.Println(e.field) fmt.Println("--") } }
This modified code will successfully change the values of the field for all elements in the array and print "foo" for each element.
The above is the detailed content of Why Doesn't Modifying Values in Go's Range Loop Change the Original Array?. For more information, please follow other related articles on the PHP Chinese website!