尽管地图始终是引用类型,但如果它们是从非指针接收器返回的呢?

huangapple go评论85阅读模式
英文:

Although maps are always reference types, what if they're returned from a non-pointer receiver?

问题

据说在Go语言中,地图(maps)是引用类型,因此当从函数中返回地图时,不需要将地图作为指针传递,以便在函数外部看到更改。但是,如果该地图是从非指针结构体的方法中返回的呢?

例如:

type ExampleMapHolder struct {
    theUnexportedMap map[string]int
}

func (emp ExampleMapHolder) TheMap() map[string]int {
    return emp.theUnexportedMap
}

如果我调用TheMap(),然后修改其中的一个值,即使接收器不是指针,这个更改是否会在其他地方可见?我想它会返回一个属于ExampleMapHolder副本的地图的引用,但是在文档中没有找到明确的答案。

英文:

Supposedly maps are reference types in Go, so when returning them from functions, you don't need to pass as a pointer to the map in order for the changes to be visible outside the function body. But what if said map is returned from a method on a non-pointer struct?

For example:

type ExampleMapHolder struct {
    theUnexportedMap map[string]int
}

func (emp ExampleMapHolder) TheMap() map[string]int {
    return emp.theUnexportedMap
}

If I make a call to TheMap(), and then modify a value in it, will this change be visible elsewhere even though the receiver is not a pointer? I imagine it would return a reference to a map that belonged to a copy of ExampleMapHolder, but haven't been able to find an explicit answer in the docs.

答案1

得分: 2

为什么你不直接检查一下呢?

emp := ExampleMapHolder{make(map[string]int)}
m := emp.TheMap()
m["a"] = 1
fmt.Println(emp) // 输出 {map[a:1]}

Playground: http://play.golang.org/p/jGZqFr97_y

英文:

Why won't you just check it?

emp := ExampleMapHolder{make(map[string]int)}
m := emp.TheMap()
m["a"] = 1
fmt.Println(emp) // Prints {map[a:1]}

Playground: http://play.golang.org/p/jGZqFr97_y

huangapple
  • 本文由 发表于 2015年6月18日 20:49:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/30915821.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定