如何解释golang slice range的现象 [英] How to explain golang slice range's phenomenon

查看:17
本文介绍了如何解释golang slice range的现象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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)
    }
}

结果:

地图[艾伦:0xc42006a0c0 汤姆:0xc42006a0c0]

map[Allen:0xc42006a0c0 Tom:0xc42006a0c0]

艾伦和{汤姆 23}

汤姆和{汤姆 23}

如何解释 Slice 的现象,在我看来,stu 应该是 s 的每个成员的地址,但是从结果来看,s 的地址是一样的.

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.

推荐答案

应用程序正在获取局部变量 stu 的地址.更改代码以获取切片元素的地址:

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

这篇关于如何解释golang slice range的现象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆