Go Fallthrough Statement Explained
In Go language, the fallthrough keyword is used to explicitly execute the next case branch in a switch statement, regardless of whether the next case’s condition is met. Typically, when a case condition in a switch statement is met, the corresponding case branch is executed and the switch statement automatically exits. However, if the fallthrough keyword is used in a case branch that satisfies the condition, the execution continues to the next case branch without any condition check.
Here is an example of using the “fallthrough” keyword:
package main
import "fmt"
func main() {
num := 2
switch num {
case 1:
fmt.Println("第一个case")
fallthrough
case 2:
fmt.Println("第二个case")
fallthrough
case 3:
fmt.Println("第三个case")
default:
fmt.Println("默认case")
}
}
The output is:
第二个case
第三个case
In the example above, the value of num is 2, satisfying the condition of case 2. However, since the first case branch uses the fallthrough keyword, the next case branch will also be executed. Therefore, the output result is the second and third cases.
It’s important to note that when using the fallthrough keyword, the code in subsequent case branches will be executed without any condition checks. Therefore, the fallthrough keyword should be used carefully to avoid unexpected results.