How to explain golang slice range's phenomenon [duplicate]

夙愿已清 提交于 2021-02-13 17:40:17

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!