douxuzui4590 2017-02-08 07:51
浏览 5

去地图查找返回元素的副本?

It seems like Go's map lookup returns a copy of the element. Can't seem to find this described in the language spec. I wrote a program as below:

type T struct { n int }

m := make(map[string]T)
t := T{123}
m["123"] = t
t0 := m["123"]
t1 := m["123"]
t0.n = 456
t1.n = 789
fmt.Println(t, t0, t1)

I got the output as: {123} {456} {789}. Looks like every time a copy of the element is returned?

  • 写回答

1条回答 默认 最新

  • duanguoping2016 2017-02-08 07:54
    关注

    Go does not pass references, ever. It either passes values, making copies on assignment, or these values can be pointers, in which case the copy is of a pointer, which is practically a reference.

    So let's say we have

    type Foo struct {
       Bar string
    }
    

    if we make a map of values, i.e.

    m := map[string]Foo{}
    

    then map accesses return a copy of a Foo, or a zero valued Foo:

    m["x"] = Foo{"hello"}
    
    y := m["x"]
    

    y is now a different object than what's in the map, so changing its Bar won't affect the object in the map.

    But, if we make the map a map of pointers:

    m := map[string]*Foo{}
    

    and then access it:

    m["x"] = &Foo{"bar"}
    y := m["x"]
    

    y is now a pointer to the same object as in the map. We can change its Bar and it will affect the map:

    y.Bar = "wat"
    fmt.Println(m["x"].Bar)
    
    // Will print "wat"
    

    Playground example.

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度