在golang中正确使用派生的映射类型索引的方法是什么?

huangapple go评论90阅读模式
英文:

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
}

huangapple
  • 本文由 发表于 2014年4月22日 13:07:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/23210824.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定