英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论