GO 面试题

1.以下代码有什么问题,说明原因

type student struct {
    Name string
    Age  int
}

func pase_student() {
    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
    }
}

答:
阐述问题:会存在问题,最终m存储的值都会相同,即
m["zhou"] = &{Name: "zhou", Age: 24}
m["li"] = &{Name: "zhou", Age: 24}
m["wang"] = &{Name: "zhou", Age: 24}

分析问题:
for range代码被翻译成下面代码

for_temp := range
len_temp := len(for_temp)
for index_temp = 0; index_temp < len_temp; index_temp++ {
    value_temp = for_temp[index_temp]
    index = index_temp
    value = value_temp
    m[value.Name] = &value
}

则每一次循环中,存储起来的value指针其实都是同一个。

解决问题:

for _, stu := range stus {
    temp := stu
    m[stu.Name] = &temp
}

Go Range内幕