简体   繁体   English

尽管映射总是引用类型,但如果它们是从非指针接收器返回的呢?

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

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.据说映射是 Go 中的引用类型,因此当从函数返回它们时,您不需要作为指向映射的指针传递,以便在函数体外部可见更改。 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?如果我调用TheMap() ,然后修改其中的值,即使接收者不是指针,这种更改是否在其他地方可见? 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.我想它会返回对属于 ExampleMapHolder 副本的地图的引用,但无法在文档中找到明确的答案。

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游乐场: http : //play.golang.org/p/jGZqFr97_y

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM