go - Go switch/cases 是否失败?

标签 go switch-statement fall-through

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

最佳答案

不,Go switch 语句不会自动失败。如果您确实希望它失败,则必须明确使用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

关于go - Go switch/cases 是否失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40821855/

相关文章:

go - 将 Windows 64 (TDM-GCC-64) 上的 Go 交叉编译为 .linux 文件,但尽管 GOOS=linux 仍继续编译为 .exe 文件

javascript - Switch 语句比较用户输入 Javascript

Swift:在 Switch 语句中使用比较运算符

switch-statement - 在 Dart 中切换失败

python - Python 字典中 switch/case 替换失败

go - 将RFC3339字符串解析为时间时,无法将时间解析为T

mongodb - 在出现错误的情况下重新创建 mgo session (读取 tcp 127.0.0.1 :46954->127. 0.0.1:27017: i/o 超时)

mongodb - 如何使用 golang 根据用户条件对 mongodb 集合应用多个过滤器

javascript - Switch 语句可以与退格键配合使用,而 if 语句则不能吗?

c# - 为什么不对 switch 语句强制执行显式 fall-through 而不是显式 break?