Home > Backend Development > Golang > How Does Go's Slice Range Loop Affect Address Assignment in Maps?

How Does Go's Slice Range Loop Affect Address Assignment in Maps?

Mary-Kate Olsen
Release: 2024-12-03 07:06:09
Original
283 people have browsed it

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)
    }
}
Copy after login

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]
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template