2

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?

user7610
  • 25,267
  • 15
  • 124
  • 150

1 Answers1

6

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

Kenny Grant
  • 9,360
  • 2
  • 33
  • 47
  • I want to differentiate so that I can debug things more easily. When I debug, I want `int32` to appear as a number and `rune` to appear as a quoted character. But, because I can't distinguish them, both `rune`s and `int32`s have to be displayed in the same way. Either both get displayed as numbers (the default for `fmt.Sprintf("%#v", val)`), or both will be displayed as a quoted characters (using `"%q"`). These choices are just weird, and I wish `rune` and `int32` were really separate types. – Chaim Leib Halbert Oct 18 '17 at 23:44