Niv*_*vas -5 go switch-statement fall-through
我是Golang的新手,我发现switch case声明不需要break声明来停止评估案例.
那么,我想知道如何在go中实现这种穿透行为?
对此有一个确切的fallthrough说法.
看这个例子:
fmt.Println("First round: without fallthrough")
switch 1 {
case 0:
fmt.Println(0)
case 1:
fmt.Println(1)
case 2:
fmt.Println(2)
case 3:
fmt.Println(3)
}
fmt.Println("Second round: with fallthrough")
switch 1 {
case 0:
fmt.Println(0)
fallthrough
case 1:
fmt.Println(1)
fallthrough
case 2:
fmt.Println(2)
fallthrough
case 3:
fmt.Println(3)
}
Run Code Online (Sandbox Code Playgroud)
输出(在Go Playground上试试):
First round: without fallthrough
1
Second round: with fallthrough
1
2
3
Run Code Online (Sandbox Code Playgroud)
(注意,我没有fallthrough在最后使用语句case,因为这将是一个编译时错误:"在开关中无法通过最终案例".)