Question:
In Go, attempting to use the fallthrough statement in a type switch raises an error. Why is fallthrough not allowed in this context?
Answer:
In a type switch, the variable being switched on changes type depending on the specific case that is executed. For example, the variable i in the following code has a type that depends on the case that is invoked:
var x interface{} 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!") }
If fallthrough were allowed, how would it be expected to behave? In the case of bool, i is typed as bool. However, in the case of string, i becomes typed as string.
Allowing fallthrough would require either magical type morphing (impossible) or variable shadowing (with no meaningful value). Consider the following example:
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 is the type here? Should be "string", but what if it falls through from bool? }
The only possible solution would be to have fallthrough implicitly cast subsequent cases to interface{}, but this would be confusing and poorly defined.
If the desired type-checking behavior for switch-case expressions is essential, it can be implemented with existing functionality:
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 }
The above is the detailed content of Why is Fallthrough Not Allowed in Go's Type Switch?. For more information, please follow other related articles on the PHP Chinese website!