繁体   English   中英

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

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

据说映射是 Go 中的引用类型,因此当从函数返回它们时,您不需要作为指向映射的指针传递,以便在函数体外部可见更改。 但是如果所述映射是从非指针结构上的方法返回的呢?

例如:

type ExampleMapHolder struct {
    theUnexportedMap map[string]int
}

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

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

你为什么不检查一下?

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

游乐场: http : //play.golang.org/p/jGZqFr97_y

暂无
暂无

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

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