1

次のコードを持つ

var v interface{}
v = rune(1)

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

コンパイルエラーが発生します

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

代わりにルーンを独自の型でラップすると、型スイッチがコンパイルされて機能します

type myrune rune

var v interface{}
v = myrune(1)

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

https://play.golang.org/p/2lMRlpCLzXを参照してください

何故ですか?タイプスイッチでルーン文字と int32 を区別するにはどうすればよいですか?

4

1 に答える 1