gpt4 book ai didi

go - switch 语句中的 falltrough 行为

转载 作者:数据小太阳 更新时间:2023-10-29 03:33:26 26 4
gpt4 key购买 nike

我正在阅读 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 但通过 流到下一个子句执行落空

关于go - switch 语句中的 falltrough 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31090405/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com