pointers - 将 map 的值指针添加到 slice 的行为

标签 pointers dictionary go slice

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/

相关文章:

http - 取消 Http 处理程序请求

c++ - 结构和函数(通过引用传递)

c - 从文本中删除数字的程序

c# - .NET HashTable 与 Dictionary - Dictionary 能一样快吗?

Java 正则表达式在多个定界符上拆分,包括其他定界符的子字符串

dictionary - 我的程序的map/zipmap部分会消耗太多内存吗?

c++ - 对象的内部表示

c++ - 指针包含什么类型的数据

windows - 从 Go 代码调用 typeperf 以接收系统信息

javascript - 如何整合Golang后端和Javascript(three.js)前端?