for 循环
2020-03-20 本文已影响0人
anthonydan
经典坑
错误:得到的全是相同的地址
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)
}