Home >Backend Development >Golang >How to Modify Original Values During Range Iterations in Go?
When iterating over a range of values, it's common to want to modify the original values rather than just working with copies. However, by default, the range construct returns a copy of each value.
package main import "fmt" type MyType struct { field string } func main() { var array [10]MyType for _, e := range array { e.field = "foo" } for _, e := range array { fmt.Println(e.field) fmt.Println("--") } }
In the above code, the "field" field of each element in the array is not modified because the range copies the value into the e variable.
To modify the original values, you cannot use the range construct to iterate over the values. Instead, you must use the array index.
package main import "fmt" type MyType struct { field string } func main() { var array [10]MyType for idx, _ := range array { array[idx].field = "foo" } for _, e := range array { fmt.Println(e.field) fmt.Println("--") } }
By using the array index, you are directly accessing the original values in the array and can modify them as needed.
The above is the detailed content of How to Modify Original Values During Range Iterations in Go?. For more information, please follow other related articles on the PHP Chinese website!