douting0585 2017-03-10 11:04
浏览 34
已采纳

如何在Go中更新地图值

I want to build a map with string key and struct value with which I'm able to update struct value in the map identified by map key.

I've tried this and this which doesn't give me desired output.

What I really want is this:

Received ID: D1 Value: V1
Received ID: D2 Value: V2
Received ID: D3 Value: V3
Received ID: D4 Value: V4
Received ID: D5 Value: V5

Data key: D1 Value: UpdatedData for D1
Data key: D2 Value: UpdatedData for D2
Data key: D3 Value: UpdatedData for D3
Data key: D4 Value: UpdatedData for D4
Data key: D5 Value: UpdatedData for D5

Data key: D1 Value: UpdatedData for D1
Data key: D2 Value: UpdatedData for D2
Data key: D3 Value: UpdatedData for D3
Data key: D4 Value: UpdatedData for D4
Data key: D5 Value: UpdatedData for D5
  • 写回答

1条回答 默认 最新

  • dongqian9013 2017-03-10 11:08
    关注

    You can't change values associated with keys in a map, you can only reassign values.

    This leaves you 2 possibilities:

    1. Store pointers in the map, so you can modify the pointed object (which is not inside the map data structure).

    2. Store struct values, but when you modify it, you need to reassign it to the key.

    1. Using pointers

    Storing pointers in the map: dataManaged := map[string]*Data{}

    When you "fill" the map, you can't use the loop's variable, as it gets overwritten in each iteration. Instead make a copy of it, and store the address of that copy:

    for _, v := range dataReceived {
        fmt.Println("Received ID:", v.ID, "Value:", v.Value)
        v2 := v
        dataManaged[v.ID] = &v2
    }
    

    Output is as expected. Try it on the Go Playground.

    2. Reassigning the modified struct

    Sticking to storing struct values in the map: dataManaged := map[string]Data{}

    Iterating over the key-value pairs will give you copies of the values. So after you modified the value, reassign it back:

    for m, n := range dataManaged {
        n.Value = "UpdatedData for " + n.ID
        dataManaged[m] = n
        fmt.Println("Data key:", m, "Value:", n.Value)
    }
    

    Try this one on the Go Playground.

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

报告相同问题?

悬赏问题

  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多