我想知道为什么 golang 中的类型 switch 语句中不允许失败。
根据规范:“类型开关中不允许使用“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!")
}
}