Go switch/cases 是否失败?

Do Go switch/cases fallthrough or not?

当您到达一个 Go 案例的末尾时会发生什么,它会失败到下一个,还是假设大多数应用程序不想失败?

不,默认情况下 Go switch 语句不会失败。如果您 do 希望它失败,则必须明确使用 fallthrough 语句。来自 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.

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

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

输出:

I will print
I will also print

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

中断保留为默认值,但不会掉线。如果您想进入下一个匹配案例,您应该明确提及 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 
}