dongyu3967 2014-04-22 05:07
浏览 23
已采纳

在Golang中使用派生地图类型索引的正确方法

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?

  • 写回答

2条回答 默认 最新

  • duandingcu7010 2014-04-22 05:13
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?