dongpeiwei8589 2019-07-09 12:23
浏览 538
已采纳

Go是否按值或作为指针将对象存储在map中?

I have the following map:

var conns map[string]Conn

Where as you know, Conn is a custom type. And my map stores values of types Conn, as the declaration shows. For storing them in a map, I do this:

conns["127.0.0.1"] = Conn{}

But my question is does Go, under the hood, store a pointer to the Conn object or it actually stores the value?

  • 写回答

1条回答 默认 最新

  • dongshao8471 2019-07-09 12:38
    关注

    structs are stored by value. Accesses to conns["127.0.0.1"] will give you a copy of the Conn struct.

    If you try to modify the struct like this, the struct at conns["127.0.0.1"] will remain unchanged until you overwrite the map entry with the newly modified struct:

    c := conns["127.0.0.1"]
    c.x = y
    
    // `c` now contains different content to `conns["127.0.0.1"]`!
    
    // To ensure conns["127.0.0.1"] is updated, either overwrite or use a point.
    conns["127.0.0.1"] = c // overwrite
    

    This is why when you modify the struct, the struct in the map remains unchanged until you overwrite the map entry with the new struct.

    Instead, you can store the pointer to the struct. This allows direct modification of the struct.

    So if you change the type of conns from map[string]Conn to map[string]*Conn, the first two lines of the above code would update the struct in the map.

    More information can be found here: https://www.ardanlabs.com/blog/2017/07/interface-semantics.html

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

报告相同问题?

悬赏问题

  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题