duanfu2562 2016-11-21 22:39
浏览 55
已采纳

地图值指针添加到切片的行为

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
", v)
        i++
    }
    for _, k := range array {
        fmt.Printf("Value: %d
", *k)
    }
}

The output is not:

Value: 912
Value: 3711
Value: 2138
Value: 1908

Instead, the output maybe like:

Value: 912
Value: 912
Value: 912
Value: 912

Can someone explain why the results are like the above?

  • 写回答

2条回答 默认 最新

  • douwei7471 2016-11-21 23:12
    关注

    Quoting from this doc:

    [...] each iteration of the loop uses the same instance of the variable v, so each closure shares that single variable [...]

    In other words, the loop variable v is reused in all iterations, so your assigning the same pointer to all your slice elements.

    Variables declared inside the loop won't be recycled like that, so this will work as you would expect:

    for _, v := range m {
        vv := v
        array[i] = &vv
        fmt.Printf("Add to array: %d
    ", v)
        i++
    }
    

    Btw, you haven't explained why you want to use *int as the type of the values. All this would be simpler if you used simply int values.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么