例子:
go
func main() {
yourList := [...]int{1, 2, 3}
yourMap1 := make(map[int]*int)
yourMap2 := make(map[int]*int)
for key, value := range yourList {
// 修改前
yourMap1[key] = &value
// 修改后
tmp := value
yourMap2[key] = &tmp
fmt.Println(value, &value, tmp, &tmp)
}
fmt.Println(yourMap1)
fmt.Println(yourMap2)
}
//1 0xc000020090 1 0xc000020098
//2 0xc000020090 2 0xc0000200a8
//3 0xc000020090 3 0xc0000200c0
//map[0:0xc000020090 1:0xc000020090 2:0xc000020090]
//map[0:0xc000020098 1:0xc0000200a8 2:0xc0000200c0]
前者地址一直没变,但后者地址会变,因为我们把值拷贝一份之后又重新取址。
注意:
-
每次都要赋值新变量即
:=
, -
如果改成这样是没用的
tmp := &value;yourMap2[key] = tmp;
也就是把地址给新变量,还是会把一样的地址赋予到map里面