duanhaodi4809 2019-06-04 00:43
浏览 61
已采纳

在go中修改地图的约定

In go, is it more of a convention to modify maps by reassigning values, or using pointer values?

type Foo struct {
    Bar int
}

Reassignment:

foos := map[string]Foo{"a": Foo{1}}
v := foos["a"]
v.Bar = 2
foos["a"] = v

vs Pointers

foos := map[string]*Foo{"a": &Foo{1}}
foos["a"].Bar = 2
  • 写回答

1条回答 默认 最新

  • duangu1868 2019-06-04 19:17
    关注

    You may be (inadvertently) conflating the matters here.

    The reason to store pointers in a map is not to make "dot-field" modifications work—it is rather to preserve the exact placements of the values "kept" by a map.

    One of the crucial properties of Go maps is that the values bound to their keys are not addressable. In other words, you cannot legally do something like

    m := {"foo": 42}
    p := &m["foo"] // this won't compile
    

    The reason is that particular implementations of the Go language¹ are free to implement maps in a way which allow them to move around the values they hold. This is needed because maps are typically implemented as balanced trees, and these trees may require rebalancing after removing and/or adding new entries. Hence if the language specification were to allow taking an address of a value kept in a map, that would forbid the map to move its values around.

    This is precisely the reason why you cannot do "in place" modification of map values if they have struct types, and you have to replace them "wholesale".

    By extension, when you add an element to a map, the value is copied into a map, and it is also copied (moved) when the map shuffles its entries around.

    Hence, the chief reason to store pointers into a map is to preserve "identities" of the values to be "indexed" by a map—having them exist in only a single place in memory—and/or to prevent excessive memory operations. Some types cannot even be sensibly copied without introducing a bug—sync.Mutex or a struct type containing one is a good example.

    Getting back to your question, using pointers with the map for the purpose you propose might be a nice hack, but be aware that this is a code smell: when deciding on values vs pointers regarding a map, you should be rather concerned with the considerations outlined above.


    ¹ There are at least two of them which are actively maintained: the "stock" one, dubbed "gc", and a part of GCC.

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

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)