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
}
則每一次循環(huán)中竭贩,存儲起來的value指針其實都是同一個。
解決問題:
for _, stu := range stus {
temp := stu
m[stu.Name] = &temp
}