Search code examples
goint32runetype-switch

How do I distinguish a rune and int32 values in a typeswitch?


Having the following code

var v interface{}
v = rune(1)

switch v.(type) {
    case int32:
        fmt.Println("int32")
    case rune:
        fmt.Println("rune")
}

I get a compilation error

tmp/sandbox193184648/main.go:14: duplicate case rune in type switch
    previous case at tmp/sandbox193184648/main.go:12

If I instead wrap the rune in my own type, the type-switch compiles and works

type myrune rune

var v interface{}
v = myrune(1)

switch v.(type) {
case int32:
    fmt.Println("int32")
case myrune:
    fmt.Println("rune")
}

see https://play.golang.org/p/2lMRlpCLzX

Why is that? How can I distinguish a rune and int32 in a type-switch?


Solution

  • It's an alias for int32, apparently you can't distinguish them. If you really needed to, defining your own type to wrap one of them would be the way to go, why did you need to do so?

    No, you can't differentiate them. rune is an alias for int32, and byte is an alias for uint8.

    https://groups.google.com/forum/m/#!searchin/golang-nuts/Rune/golang-nuts/jbWUrsQ-Uws