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

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

报告相同问题?

悬赏问题

  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗