How to access map values in GO?

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

How to access map values in GO?

问题

你好!以下是代码的翻译:

如何访问以下代码中的映射值?代码片段是自动生成的,所以我无法修改它。我尝试了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,
}

错误信息:
cannot use int(api.OpType_UNKNOWN) (type int) as type int32 in map index

请注意,错误信息中提到的int(api.OpType_UNKNOWN)是将OpType_UNKNOWN转换为int类型,而不是int32类型。你可以尝试将其更改为int32(OpType_UNKNOWN)来解决此错误。

英文:

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

得分: 7

Go对类型要求非常严格。你的映射(maps)中所有的键都是int32类型的,而你试图使用OpType类型的值来访问它们。OpType是int32类型并不重要。

你可以将OpType转换为int32类型,这样就可以正常工作了。

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

@nos的评论是一个不错的方法,这可能是你在这种情况下想要的。

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

英文:

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

huangapple
  • 本文由 发表于 2015年12月14日 00:21:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/34253313.html
匿名

发表评论

匿名网友

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

确定