5

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 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

3 Comments

Alternatively, make the map use OpType instead of int32, map[OpType]string{
I think it worth to do a bit of nit-picking: OpType is not int32: it only shares the internal representation of the values of its type with int32. The crucial point is that type B A does not make B "inherit" any methods of A. This does not matter for int32, which does not have methods, but is important to know when dealing with custom types.
I mean, that's the reason why Go does allow type-conversion from int32 to OpType (the internal representation of the value is the same) but does not allow to assign a value of OpType to a receiver of type int32: if it would be allowed, the receiver might want to call a method defined for its type but the value passed to it would not have it in its (different) type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.