drj14664 2015-12-12 16:27
浏览 41
已采纳

从golang中的地图生成字典地图

This is the code that I am trying to make run on playground: http://play.golang.org/p/zX1G50txzf

I have this map:

map[producer:Tesla model:Model S year:2015]

and I want turn this into this :

[map[field:producer value:Tesla] map[field:model value:S] map[field:year value:2015]]

but in the end I will get this:

[map[field:year value:2015] map[field:year value:2015] map[field:year value:2015]]

Looks like every time the loop iterate over the original map, I am copying the reference instead of the value, so I end up with the last value replicated 3 times, instead of one of each.

What am I missing here?

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • dongsui4658 2015-12-12 16:28
    关注

    A new temp map needs to be created on each iteration of the loop. Otherwise, you are just overwriting the same map:

    for key, value := range res {
        temp := make(map[string]interface{})
        // ...
    }
    

    https://play.golang.org/p/v-RaL2fswp

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器