问题
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)
}
}
result:
map[Allen:0xc42006a0c0 Tom:0xc42006a0c0]
Allen &{Tom 23}
Tom &{Tom 23}
How to explain Slice's phenomenon, in my opinion, stu should be the address of every member of s, but from the results, s has the same address.
回答1:
The application is taking the address of the local variable stu
. Change the code to take the address of the slice element:
for i := range s {
m[s[i].Name] = &s[i]
}
https://play.golang.org/p/0izo4gGPV7
来源:https://stackoverflow.com/questions/46169351/how-to-explain-golang-slice-ranges-phenomenon