当您到达一个 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
关于go - Go switch/cases 是否失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40821855/