gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:40:09 25 4
gpt4 key购买 nike

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

例如:

type ExampleMapHolder struct {
theUnexportedMap map[string]int
}

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

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

最佳答案

你为什么不检查一下呢?

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

关于pointers - 尽管映射始终是引用类型,但如果它们是从非指针接收器返回的呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30915821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com