dongpeiwei8589
2019-07-09 12:23 阅读 145
已采纳

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 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

    点赞 评论 复制链接分享

相关推荐