做ppt高手_一定要常去这八个网站,企业网站背景颜色,成都做企业网站,新闻发布会策划流程在 Go 语言中#xff0c;switch 语句设计得更加简洁和直观#xff0c;因此不需要显式使用 break 语句来终止一个分支。这种设计决策源于 Go 语言的一些设计哲学和目标#xff0c;主要包括#xff1a; 自动终止#xff1a; Go 语言的 switch 语句会在每个 case 执行完成后自…在 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)}
}