英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论