英文:
Proper way of using derived map type index in golang
问题
这可能是一个初学者的问题。代码如下:
type MYMAP map[int]int
func (o *MYMAP) dosth(){
//这将无法编译通过
o[1]=2
}
错误信息:invalid operation: o[1] (index of type *MYMAP)
如何访问 MYMAP 的底层类型 map?
英文:
It could be a beginner's question. Code is like,
type MYMAP map[int]int
func (o *MYMAP) dosth(){
//this will fail to compile
o[1]=2
}
error message: invalid operation: o[1] (index of type *MYMAP)
How to access the underlying type of MYMAP as map?
答案1
得分: 25
问题不在于它是一个别名,而在于它是一个指向映射的指针。
Go语言不会自动解引用指针来访问映射或切片,就像它对方法调用那样。将o[1]=2
替换为(*o)[1]=2
将起作用。不过,你应该考虑为什么要(实际上)使用指向映射的指针。这样做可能有很好的理由,但通常不需要指向映射的指针,因为映射是“引用类型”,这意味着你不需要指针来查看它们在程序中的变化副作用。
英文:
The problem isn't that it's an alias, it's that it's a pointer to a map.
Go will not automatically deference pointers for map or slice access the way it will for method calls. Replacing o[1]=2
with (*o)[1]=2
will work. Though you should consider why you're (effectively) using a pointer to a map. There can be good reasons to do this, but usually you don't need a pointer to a map since maps are "reference types", meaning that you don't need a pointer to them to see the side effects of mutating them across the program.
答案2
得分: 5
一个简单的修复方法是去掉指针,只需将 o *MYMAP
改为 o MYMAP
。
type MYMAP map[int]int
func (o MYMAP) dosth(){
o[1]=2
}
英文:
An easy fix could be done by getting rid of pointer, just change o *MYMAP
to o MYMAP
type MYMAP map[int]int
func (o MYMAP) dosth(){
o[1]=2
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论