2019-07-09 12:23 阅读 145


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[""] = 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[""] will give you a copy of the Conn struct.

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

    c := conns[""]
    c.x = y
    // `c` now contains different content to `conns[""]`!
    // To ensure conns[""] is updated, either overwrite or use a point.
    conns[""] = 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:

    点赞 评论 复制链接分享