Go-关键词-fallthrough

576 阅读1分钟

fallthrough

概念

fallthrough只能用于switch中且只能在每个case分支中最后一行出现,作用是如果这个case分支被执行,将会继续执行下一个case而不会判断下一个分支的case条件是否成立。

代码示例

代码

package main

func main() {
	age := 10

	switch age {
	case 9, 10, 11:
		println("分支9,10,11")
		fallthrough
	case 0, 1, 2:
		println("分支0,1,2")
	case 3, 4, 5:
		println("分支3,4,5")
	case 6, 7, 8:
		println("分支6,7,8")
	}
}

输出结果

分支9,10,11
分支0,1,2

解读

age值为10,所以case 9,10,11将会执行,但后面跟了fallthrough关键字,虽然case 0,1,2不成立,但受fallthrough影响其依然会被执行,执行完并退出。

建议

代码可优化为如下:

func main() {
	age := 10

	switch age {
	case 9, 10, 11, 0, 1, 2:
		println("分支9,10,11")
		println("分支0,1,2")
	case 3, 4, 5:
		println("分支3,4,5")
	case 6, 7, 8:
		println("分支6,7,8")
	}
}

其实实际编码过程中fallthrough的应用并不多,可利用更加明确的case列表取代fallthrouth,因此在真正打算使用fallthrough之前,可以先想想能否使用更为简洁、清晰的case表达式列表替代。