Do Go switch/cases fallthrough or not?

huangapple go评论69阅读模式
英文:

Do Go switch/cases fallthrough or not?

问题

当你到达Go语言中的一个case的结尾时,会发生什么?它会继续执行下一个case吗?还是默认情况下大多数应用程序都不希望继续执行下去?

英文:

What happens when you reach the end of a Go case, does it fall through to the next, or assume that most applications don't want to fall through?

答案1

得分: 144

不,Go的switch语句不会自动执行下一个case。如果你希望执行下一个case,必须显式地使用fallthrough语句。根据规范

在case或default子句中,最后一个非空语句可以是一个(可能带标签的)"fallthrough"语句,以指示控制流从该子句的末尾流向下一个子句的第一个语句。否则,控制流将流向switch语句的末尾。"fallthrough"语句可以出现在表达式switch的除最后一个子句外的所有子句的最后一条语句中。

例如(很抱歉,我实在想不出一个真实的例子):

switch 1 {
case 1:
    fmt.Println("我会打印")
    fallthrough
case 0:
    fmt.Println("我也会打印")
}

输出:

我会打印
我也会打印

你可以在这里查看示例代码:https://play.golang.org/p/va6R8Oj02z

英文:

No, Go switch statements do not fall through automatically. If you do want it to fall through, you must explicitly use a fallthrough statement. From the spec:

> 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.

For example (sorry, I could not for the life of me think of a real example):

switch 1 {
case 1:
	fmt.Println("I will print")
	fallthrough
case 0:
	fmt.Println("I will also print")
}

Outputs:

I will print
I will also print

https://play.golang.org/p/va6R8Oj02z

答案2

得分: 18

保留了break作为默认选项,但不再使用fallthrough。如果你想要在匹配到一个case后继续执行下一个case,你应该明确地使用fallthrough关键字。

switch choice {
case "optionone":
    // 一些指令
    fallthrough // 控制流将不会从这个case中跳出,而是继续执行下一个case
case "optiontwo":
   // 一些指令
default: 
   return 
}
英文:

Break is kept as a default but not fallthrough. If you want to get onto the next case for a match, you should explicitly mention fallthrough.

switch choice {
case "optionone":
    // some instructions 
    fallthrough // control will not come out from this case but will go to next case.
case "optiontwo":
   // some instructions 
default: 
   return 
}

huangapple
  • 本文由 发表于 2016年11月27日 02:49:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/40821855.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定