在 Go 语言中,switch 语句设计得更加简洁和直观,因此不需要显式使用 break 语句来终止一个分支。这种设计决策源于 Go 语言的一些设计哲学和目标,主要包括:
-
自动终止:
Go 语言的switch语句会在每个case执行完成后自动终止,不需要像 C 或 Java 中那样使用break来显式地中断当前分支。这意味着你不需要担心遗漏break导致意外的“贯穿”(fall-through)行为。 -
避免“贯穿”:
在 Go 语言中,switch语句的默认行为是结束当前case后自动跳出switch语句。这种设计可以减少因忘记添加break语句而导致的潜在错误。 -
显式
fallthrough:
如果你确实希望在一个case执行后继续执行下一个case,可以使用fallthrough关键字。这样可以明确地指示编译器要进行“贯穿”,避免了无意中出现这种情况。
示例:
func main() {testSwitch(2)
}
func testSwitch(i int) {switch i {case 1:fmt.Println("one")case 2:fmt.Println("two")fallthroughcase 3:fmt.Println("three")case 4:fmt.Println("four")default:fmt.Println("none")}
}# 输出:
two
three
在这个例子中,fallthrough 关键字使得 case 2 执行完成后,程序继续执行 case 3 的代码块。这与传统的 switch 语句中需要手动添加 break 的做法不同。
fallthrough 使用注意事项
1、fallthrough 只能用于普通的 case
fallthrough 不能用于 default 分支。它只能在普通的 case 分支中使用
switch x {
case 1:// validfallthrough
default:// fallthrough //Cannot use 'fallthrough' in the final case of the 'switch' statement
}
2、不能用于 case 中的代码块:
switch x {
case 1:{fmt.Println("Case 1")//fallthrough // The 'fallthrough' statement is out of place}
case 2:fmt.Println("Case 2")
}
3、只能用于普通的 case 语句,而不能用于类型断言的 switch 语句中的 case。
func printType(i interface{}) {switch i.(type) {case int:fmt.Println("Integer")case string:fmt.Println("String")//fallthrough //Cannot use 'fallthrough' in the type switchcase bool:fmt.Println("Boolean")default:fmt.Println("Unknown type")}
}
