Returning Addresses instead of Values for Range References
Consider the situation where a range statement returns a copy of a value instead of the original address. This can lead to unexpected behavior, as seen in the following Go code:
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 this example, the intent is to modify the "field" property of each element in the array. However, since the range statement returns a copy of the value, the changes are made to a local copy and don't affect the original array. As a result, the output shows all "field" properties as having the default value.
To address this issue, you cannot return the address of the item in a range loop. Instead, you should iterate through the array using the index, as shown below:
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 index instead of the value in the for loop, you ensure that the changes made to the "field" property are reflected in the original array.
The above is the detailed content of Why Does My Go Range Loop Not Modify Array Elements?. For more information, please follow other related articles on the PHP Chinese website!