douyan6958 2014-11-18 14:05
浏览 26

为什么地图值即使不是指针也会发生变化-Golang

I'm trying to test a method. Its signature is func (gv *myType) Update(all map[string][]SomeType) error

Although the test fails (the expected value doesn't match the received value) I've found that also the map it receives(allSub) is "updated" after the method is evaluated. Here is the code:

t.Logf("allsub %v", allSub)
if err := gv.Update(allSub); err != nil {
    t.Error(err)
    return
}
if !reflect.DeepEqual(egv, gv) {
    t.Errorf("allSub %v", allSub)
    return
}

The output

mth_test.go:265: allsub map[b:[{1 3 3}] a:[{1 0 0} {1 2 0}]]
mth_test.go:271: allSub map[a:[{1 2 0}]]

As you can see on t.Logf("allsub %v", allSub) we have map[b:[{1 3 3}] a:[{1 0 0} {1 2 0}]] and then after the evaluation if !reflect.DeepEqual(egv, gv) allSub becomes allSub map[a:[{1 2 0}]]. This drives me crazy and I'm wondering how is this possible? allSub is not a pointer.

  • 写回答

1条回答 默认 最新

  • douzong5057 2014-11-19 20:29
    关注

    Map, slice, channels are reference types. The spec is in-process to become clearer about this but basically the implementation of these builtin types entails a reference to an underlying data structure.

    So you can consider that an object of type map is actually a reference to an associative array.

    Effective Go has a little paragraph on it : https://golang.org/doc/effective_go.html#maps

    I quote :

    Like slices, maps hold references to an underlying data structure. If you pass a map to a function that changes the contents of the map, the changes will be visible in the caller.

    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集