Home >Backend Development >Golang >How Does Go's Slice Range Loop Affect Address Assignment in Maps?
Understanding the Behavior of Go Slice Ranges
In Go, slices are a fundamental data structure that provide efficient and dynamic storage of elements. When working with slices, it's essential to comprehend the behavior of range loops.
Consider the following code snippet:
type student struct { Name string Age int } func main() { m := make(map[string]*student) s := []student{ {Name: "Allen", Age: 24}, {Name: "Tom", Age: 23}, } for _, stu := range s { m[stu.Name] = &stu } fmt.Println(m) for key, value := range m { fmt.Println(key, value) } }
The code defines a slice of student structs and a map. It iterates over the slice using a range loop, where each element is assigned to the variable 'stu.' However, the unexpected behavior observed is that all the map entries point to the same address within the slice.
Root Cause:
The issue originates from the range loop's assignment to the variable 'stu.' When the loop iterates, 'stu' is assigned a copy of the slice element at that index. As a result, all the map entries refer to the same copied value.
Solution:
To resolve this behavior, the code should explicitly take the address of each slice element before storing it in the map:
for i := range s { m[s[i].Name] = &s[i] }
By making this change, each map entry now references the actual slice element's address, ensuring the expected behavior. This demonstrates the importance of understanding the nuances of slice range loops and how they can affect data manipulation in Go.
The above is the detailed content of How Does Go's Slice Range Loop Affect Address Assignment in Maps?. For more information, please follow other related articles on the PHP Chinese website!