美文网首页
for 循环

for 循环

作者: anthonydan | 来源:发表于2020-03-20 10:09 被阅读0次

    经典坑
    错误:得到的全是相同的地址
    type student struct {
    Name string
    Age int
    }
    func main() {
    m := make(map[string]student)
    stus := []student{
    {Name: "zhou",Age: 24},
    {Name: "li",Age: 23},
    {Name: "wang",Age: 22},
    }
    for _,stu := range stus {
    m[stu.Name] = &stu
    }
    fmt.Println(m)
    }
    正确:修改值也一样
    type student struct {
    Name string
    Age int
    }
    func main() {
    m := make(map[string]
    student)
    stus := []student{
    {Name: "zhou",Age: 24},
    {Name: "li",Age: 23},
    {Name: "wang",Age: 22},
    }
    for k,stu := range stus {
    m[stu.Name] = &stus[k]
    }
    fmt.Println(m)
    }

    相关文章

      网友评论

          本文标题:for 循环

          本文链接:https://www.haomeiwen.com/subject/bwbdyhtx.html