```
package main
import "fmt"
type student struct {
name string
age int
}
func main() {
m := make(map[string]*student)
stus := []student{
{name: "pprof.cn", age: 18},
{name: "测试", age: 23},
{name: "博客", age: 28},
}
for _, stu := range stus {
m[stu.name] = &stu
}
for k, v := range m {
fmt.Println(k, "=>", v.name)
}
}
```
这段代码为何会显示
![image.png](https://static.studygolang.com/210908/9da1209be2b5080df27c65c26a8ce04a.png)
最好的避坑方法就是:
1. 要用`*`都用`*`
2. 要不用都不用
一个用一个不用,自己把自己绕迷
```go
// 方式一
m := make(map[string]*student)
stus := []*student{}
for _, stu := range stus {
m[stu.name] = stu
}
// 方式二
m := make(map[string]student)
stus := []student{}
for _, stu := range stus {
m[stu.name] = stu
}
```
#10
更多评论