33

我想知道为什么 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!")
    }
}
4

1 回答 1

45

你希望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?
}

唯一可能的解决方案是将fallthroughcause 后面的 case 表达式保留iinterface{},但这将是一个令人困惑和错误的定义。

如果您真的需要这种行为,您已经可以使用现有功能完成此操作:

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
}
于 2012-07-17T21:45:36.627 回答