英文:
Does loading a map element in Go imply copying?
问题
假设有这样的代码片段。
mapper := make(map[int]SomeStructType)
mapper[0] = SomeStructType{}
somestruct := mapper[0] // 将 mapper[0] 加载到 'somestruct' 中
在最后一行,这是否意味着 mapper[0]
在所有情况下都被复制到 somestruct
中,即使 somestruct
之后被用作只读常量?
如果是这样,是否有办法创建一个对映射元素(这里是 mapper[0]
)的 引用,就像在 C/C++ 中一样,这样我就可以通过别名引用它,同时避免不必要的对象复制?我尝试创建一个指向映射元素的指针,但显然,Go 不允许我这样做。
英文:
Suppose there is a code snippet like this.
mapper := make(map[int]SomeStructType)
mapper[0] = SomeStructType{}
somestruct := mapper[0] // load mapper[0] to 'somestruct'
At the last line, does that mean mapper[0]
is copied to somestruct
in all situations, like even if somestruct
is ever used as a read-only constant afterward?
If so, is there any way to make a reference to a map element (mapper[0]
here) like in C/C++, so that I can reference it through an alias while avoiding unnecessary object copy? I tried to make a pointer to a map element, but apparently, Go does not allow me to do so.
答案1
得分: 2
简单的答案是不可以。在Go语言中,map的实现可能会移动数据,因此引用会失效,这是不安全的。在C语言中,你可以定义自己的数据结构,所以如何处理这个问题取决于你;而在Go语言中,map是在Go运行时实现的,它无法猜测你的意图。
我认为你正在寻找的解决方案是在map中保留指针,例如:
mapper := make(map[int]*SomeStructType)
现在访问mapper
的元素只会“复制”一个指针(通常是一个单词),这非常廉价。
somestruct := mapper[0] // 复制一个指针
在Go语言中使用指针类型非常常见,所以通过像这样定义mapper
并没有什么神奇或异常的地方。
英文:
The simple answer is NO. In Go, the map implementation may move data around, so references would get invalidated and it wouldn't be safe. In C you define your own data structure, so it's up to you how this is done; in Go, maps are implemented in the Go runtime, and it can't guess at your intent.
The solution you're looking for, I think, is keep pointers in the map, i.e.:
mapper := make(map[int]*SomeStructType)
Now accessing mapper
elements will just "copy" a pointer (typically a single word), which is very cheap.
somestruct := mapper[0] // copies a pointer
It's very common to use pointer types in Go, so you wouldn't be doing anything too magical or unusual by defining mapper
like this.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论