简体   繁体   English

如何在GO中访问地图值?

[英]How to access map values in 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. 我试过OpType_name[OpType_UNKNOWN]但是我从golang编译器得到错误。

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 错误: cannot use int(api.OpType_UNKNOWN) (type int) as type int32 in map index

Go is very strict on types. Go对类型非常严格。 Your maps all have keys with typ int32 and you are trying to access them using a value of type OpType. 你的地图都有typ int32的键,你试图使用OpType类型的值访问它们。 It doesn't matter that OpType is an int32. OpType是int32并不重要。

You can cast your OpType to int32 and make it work 您可以将OpType转换为int32并使其工作

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. 来自@nos的评论是一个很好的方法,它可能就是你想要的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM