在Go中,地图是通过价值还是通过引用传递的? [英] Are maps passed by value or by reference in Go?
问题描述
地图是通过Go中的值还是引用传递的?
定义一个函数总是可以的,但是这是一种矫枉过正?
func foo(dat * map [string] interface {}){...}
pre>
返回值的问题相同。我应该返回一个指向地图的指针,还是将该地图作为值返回?
当然是为了避免不必要的数据复制。
解决方案在这个话题中,您会找到您的答案: $ b
<一个href =https://stackoverflow.com/questions/28384343/golang-accessing-a-map-using-its-reference> Golang:使用其引用访问地图
您不需要在地图上使用指针。
地图类型是引用类型,就像指针或切片[1]
如果您需要更改会话,您可以使用指针:
map [string] * Session
https://blog.golang.org/go-maps-in-action
Are maps passed by value or reference in Go ?
It is always possible to define a function as following, but is this an overkill ?
func foo(dat *map[string]interface{}) {...}
Same question for return value. Should I return a pointer to the map, or return the map as value ?
The intention is of course to avoid unnecessary data copy.
解决方案In this thread you will find your answer :
Golang: Accessing a map using its reference
You don't need to use a pointer with a map.
Map types are reference types, like pointers or slices[1]
If you needed to change the Session you could use a pointer:
map[string]*Session
这篇关于在Go中,地图是通过价值还是通过引用传递的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!