func TestMapValuePointer2(t *testing.T) {
fmt.Println("Test Map Value Pointer 2")
m := map[string]int{"rsc": 3711, "r": 2138, "gri": 1908, "adg": 912}
n := len(m)
array := make([]*int, n)
i := 0
for _, v := range m {
array[i] = &v
fmt.Printf("Add to array: %d\n", v)
i++
}
for _, k := range array {
fmt.Printf("Value: %d\n", *k)
}
}
输出不是:
Value: 912 Value: 3711 Value: 2138 Value: 1908
相反,输出可能是这样的:
Value: 912 Value: 912 Value: 912 Value: 912
谁能解释一下为什么结果会像上面这样?
最佳答案
引自this doc :
[...] each iteration of the loop uses the same instance of the variable v, so each closure shares that single variable [...]
换句话说,循环变量 v
在所有迭代中重复使用,因此您将同一个指针分配给所有 slice 元素。
在循环中声明的变量不会像那样被回收,所以这会如你所料的那样工作:
for _, v := range m {
vv := v
array[i] = &vv
fmt.Printf("Add to array: %d\n", v)
i++
}
顺便说一句,您还没有解释为什么要使用 *int
作为值的类型。如果您只使用 int
值,所有这一切都会更简单。
关于pointers - 将 map 的值指针添加到 slice 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40730701/