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

这是为什么?如何区分类型开关中的 rune 和 int32?

4

1 回答 1

5

它是 int32 的别名,显然你无法区分它们。如果你真的需要,定义你自己的类型来包装其中一个将是你要走的路,你为什么需要这样做?

不,你无法区分它们。rune 是 int32 的别名,byte 是 uint8 的别名。

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

于 2017-03-14T19:47:29.693 回答