Home > Backend Development > Golang > Why Do Slice Range Iterations in Go Sometimes Return Copies Instead of Addresses?

Why Do Slice Range Iterations in Go Sometimes Return Copies Instead of Addresses?

DDD
Release: 2024-12-05 15:54:14
Original
238 people have browsed it

Why Do Slice Range Iterations in Go Sometimes Return Copies Instead of Addresses?

Understanding the Slice Range Phenomenon in Go

In Go, the behavior of slice ranges can be confusing. When iterating over a slice using a range clause, it's tempting to believe that the iteration variable holds the address of each element. However, this is not always the case. One such scenario is when working with structs and maps.

Consider the following code:

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

This code iterates over a slice of structs, adds a key-value pair to a map for each struct, and stores the address of the struct as the value. However, the resulting map shows that all values point to the same address.

To explain this phenomenon, we need to look at the underlying implementation of slice ranges. When a slice is iterated over using a range clause, the iteration variable receives a copy of the element from the slice. Thus, the iteration variable holds a copy of the struct, not its address.

To fix this issue and store the address of the struct in the map, the code must be modified to take the address of the slice element:

for i := range s {
    m[s[i].Name] = &s[i]
}
Copy after login

This change ensures that the iteration variable holds the address of the struct, and the map will correctly store the addresses of each struct in the slice.

The above is the detailed content of Why Do Slice Range Iterations in Go Sometimes Return Copies Instead of Addresses?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template