我想知道为什么在golang中的type switch语句中不允许发生故障。
根据specification:“类型切换不允许使用”语句,这并没有解释为什么不允许这样做。
附加的代码是为了模拟一个可能的场景,如果类型开关语句中的失败可能是有用的。
注意!这段代码不工作,它将产生错误:“不能在类型切换中失败”。我只是想知道,不允许类型切换中的allowing语句可能是什么原因。
//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!")
}
}发布于 2012-07-17 21:45:36
您希望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
}https://stackoverflow.com/questions/11531264
复制相似问题