如何区分 typeswitch 中的 rune 和 int32 值?
How do I distinguish a rune and int32 values in a typeswitch?
有如下代码
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?
它是int32的别名,显然你无法区分它们。如果你真的需要,定义你自己的类型来包装其中一个是可行的方法,你为什么需要这样做?
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
有如下代码
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?
它是int32的别名,显然你无法区分它们。如果你真的需要,定义你自己的类型来包装其中一个是可行的方法,你为什么需要这样做?
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