How to access map values ​​in GO?

How to access the map value for the following code? The code snippet is generated automatically, so I cannot change it. I tried OpType_name[OpType_UNKNOWN], but I get an 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,
}

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

+4
source share
1 answer

Go is very strict by type. Your cards have all keys with type int32, and you are trying to access them using a value of type OpType. It does not matter that OpType is int32.

You can overlay your OpType on int32 and make it work

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

Comment from @nos is a good way to go, this is probably what you want in this case.

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

+6
source

Source: https://habr.com/ru/post/1619721/


All Articles