duanmie9741 2015-12-13 16:21
浏览 36
已采纳

如何在GO中访问地图值?

How do I access the map value for the following code? The code snippet is auto generated, so I can't modify it. I have tried OpType_name[OpType_UNKNOWN] but I am getting error from the golang compiler.

type OpType int32

const (
    OpType_UNKNOWN OpType = 0
    OpType_CREATE OpType = 1
    OpType_DELETE OpType = 3
)

var OpType_name = map[int32]string{
    0: "UNKNOWN",
    1: "CREATE",
    2: "DELETE",
}
var OpType_value = map[string]int32{
    "UNKNOWN": 0,
    "CREATE": 1,
    "DELETE": 2,
}

Error: cannot use int(api.OpType_UNKNOWN) (type int) as type int32 in map index

  • 写回答

1条回答 默认 最新

  • doushi3715 2015-12-13 16:29
    关注

    Go is very strict on types. Your maps all have keys with typ int32 and you are trying to access them using a value of type OpType. It doesn't matter that OpType is an int32.

    You can cast your OpType to int32 and make it work

    func main() {
      fmt.Println(OpType_name[int32(OpType_UNKNOWN)])
    }
    

    The comment from @nos is a good way to go, it's probably what you want in this case.

    https://play.golang.org/p/dum5GiB3zS

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案