我想知道为什么 golang 中的类型 switch 语句中不允许失败。
根据specification :“类型切换中不允许使用“fallthrough”语句。”,这并没有解释为什么不允许它。
附加的代码是为了模拟一个可能的场景,即类型 switch 语句中的失败可能有用。
注意!此代码不起作用,它会产生错误:“cannot fallthrough in type switch”。我只是想知道在类型切换中不允许使用 fallthrough 语句的可能原因是什么。
//A type switch question
package main
import "fmt"
//Why isn't fallthrough in type switch allowed?
func main() {
//Empty interface
var x interface{}
x = //A int, float64, bool or string value
switch i := x.(type) {
case int:
fmt.Println(i + 1)
case float64:
fmt.Println(i + 2.0)
case bool:
fallthrough
case string:
fmt.Printf("%v", i)
default:
fmt.Println("Unknown type. Sorry!")
}
}
最佳答案
您希望 fallthrough
如何工作?在此类型切换中,i
变量的类型取决于调用的特定情况。因此,在 case bool
中,i
变量的类型为 bool
。但在 case string
中,它被键入为 string
。所以要么你要求 i
神奇地改变它的类型,这是不可能的,或者你要求它被一个新变量 i string
遮蔽,它没有任何值,因为它的值来自 x
,实际上它不是 string
。
这是一个尝试说明问题的示例:
switch i := x.(type) {
case int:
// i is an int
fmt.Printf("%T\n", i); // prints "int"
case bool:
// i is a bool
fmt.Printf("%T\n", i); // prints "bool"
fallthrough
case string:
fmt.Printf("%T\n", i);
// What does that type? It should type "string", but if
// the type was bool and we hit the fallthrough, what would it do then?
}
唯一可能的解决方案是使 fallthrough
导致后续 case 表达式将 i
保留为 interface{}
,但是这将是一个令人困惑和糟糕的定义。
如果您确实需要这种行为,您已经可以使用现有功能完成此操作:
switch i := x.(type) {
case bool, string:
if b, ok := i.(bool); ok {
// b is a bool
}
// i is an interface{} that contains either a bool or a string
}
关于switch-statement - 为什么在类型开关中不允许掉线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11531264/