与c语言、Java语言不同,在Go中,case
中不需要break
语句,在执行一个case
之后,默认地,控制立即从switch
语句中转移出来。
如果不想跳出,而是继续执行下一个case
,可以使用fallthrough
语句。
让我们写一个程序来理解fallthrough
。程序将检查输入数(75)是否小于50、100或200。
package main
import (
"fmt"
)
func number() int {
num := 15 * 5
return num
}
func main() {
switch num := number(); { //num is not a constant
case num < 50:
fmt.Printf("%d is lesser than 50\n", num)
fallthrough
case num < 100:
fmt.Printf("%d is lesser than 100\n", num)
fallthrough
case num < 200:
fmt.Printf("%d is lesser than 200", num)
}
}
在上面的程序中,num
被初始化为函数number()
的返回值。控制进入switch
内部,并对case
进行匹配。
case num < 100:
为真,程序打印75 is lesser than 100
, 下一个语句是fallthrough
, 遇到fallthrough
时,控制转移到下一个case
,case num < 200:
也为真,打印75 is lesser than 200
。程序的输出是
75 is lesser than 100
75 is lesser than 200
fallthrough
应该是一个case
中的最后一个语句。如果它出现在中间的某个地方,编译器将抛出错误fallthrough statement out of place