如何在类型切换中区分符文(rune)和 int32 值?

huangapple go评论69阅读模式
英文:

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

如果我将rune包装在自己的类型中,类型切换就可以编译并正常工作:

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?

英文:

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?

答案1

得分: 6

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

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

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

英文:

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

huangapple
  • 本文由 发表于 2017年3月15日 02:51:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/42794228.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定