golang在遍历slice中的坑

package main

import "fmt"

func main() {
	pase_student()
}

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 // 将临时变量stu的地址给map,最后所有的地址都为同样的一个值
	}

	for k, v := range m {
		fmt.Println(k, v)
	}
}

golang在遍历slice中的坑_第1张图片

所以这种使用是有问题的

 

应该改为

package main

import "fmt"

func main() {
	pase_student()
}

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 i, v := range stus {
		m[v.Name] = &stus[i] 
	}

	for k, v := range m {
		fmt.Println(k, v)
	}
}

golang在遍历slice中的坑_第2张图片

你可能感兴趣的:(GO)