为什么类型开关不允许穿透?

时间:2012-07-17 21:39:33

标签: switch-statement go

我想知道为什么golang中的类型切换语句不允许使用fallthrough。

根据specification:“类型切换中不允许使用”fallthrough“语句。”,这并没有解释为什么不允许这样做。

附加的代码是为了模拟一种可能的情况,因为类型转换语句中的漏洞可能是有用的。

注意!此代码不起作用,会产生错误:“无法通过类型切换”。我只是想知道在类型切换中不允许使用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!")
    }
}

1 个答案:

答案 0 :(得分:32)

您希望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导致后续案例表达式将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
}
相关问题