switch 语句中的 falltrough 行为

Behavior of falltrough in switch statement

我正在阅读 this book 中关于 Go 中的 switch 语句的部分。但是这个例子让我很困惑:

 package main

 import "fmt"

 func main() {
 k := 6
 switch k {
    case 4: fmt.Println("was <= 4"); fallthrough;
    case 5: fmt.Println("was <= 5"); fallthrough;
    case 6: fmt.Println("was <= 6"); fallthrough;
    case 7: fmt.Println("was <= 7"); fallthrough;
    case 8: fmt.Println("was <= 8"); fallthrough;
    default: fmt.Println("default case") 
    }
}

输出为:

was <= 6
was <= 7
was <= 8
default case

书中指出:

use the fallthrough statement to indicate that the case block following the current one has to be executed.

现在我要提问:

  1. 为什么 Go 在默认情况下进行比较,在这种情况下 k 较低?
  2. 文中提到执行了以下案例。美好的。但为什么他们不只执行匹配 k 的案例?

The Go Programming Language Specification

Switch statements

Expression switches

In an expression switch, the switch expression is evaluated and the case expressions, which need not be constants, are evaluated left-to-right and top-to-bottom; the first one that equals the switch expression triggers execution of the statements of the associated case; the other cases are skipped. If no case matches and there is a "default" case, its statements are executed. There can be at most one default case and it may appear anywhere in the "switch" statement. A missing switch expression is equivalent to the boolean value true.

ExprSwitchStmt = "switch" [ SimpleStmt ";" ] [ Expression ] "{" { ExprCaseClause } "}" .
ExprCaseClause = ExprSwitchCase ":" StatementList .
ExprSwitchCase = "case" ExpressionList | "default" .

In a case or default clause, the last non-empty statement may be a (possibly labeled) "fallthrough" statement to indicate that control should flow from the end of this clause to the first statement of the next clause. Otherwise control flows to the end of the "switch" statement. A "fallthrough" statement may appear as the last statement of all but the last clause of an expression switch.

The expression may be preceded by a simple statement, which executes before the expression is evaluated.

从上到下计算 case 表达式。 case 4case 5falsecase 6truecase 7case 8defaultfalse 但通过 fallthrough.

流到下一个子句执行