苏州网站网络营销推广,做爰片在线看网站,企业vi包含哪些内容,做网站的叫什么软件简介
switch 语句提供了一种简洁的方式来执行多路分支选择
基本使用
基本语法如下#xff1a;
switch expression {
case value1:// 当 expression 的值等于 value1 时执行
case value2:// 当 expression 的值等于 value2 switch 的每个分支自动提供了隐式的 break#x…简介
switch 语句提供了一种简洁的方式来执行多路分支选择
基本使用
基本语法如下
switch expression {
case value1:// 当 expression 的值等于 value1 时执行
case value2:// 当 expression 的值等于 value2 switch 的每个分支自动提供了隐式的 break意味着只有第一个匹配的 case 会被执行。不需要显式地在每个 case 后面加 break 如果你想要一个 case 执行后继续检查下一个 case可以使用 fallthrough 语句
switch x {
case 1:fmt.Println(x is 1)fallthrough
case 2:fmt.Println(x is 2)fallthrough
case 3:fmt.Println(x is 3)
default:fmt.Println(x is not 1, 2, or 3)
}在上面的代码中如果 x 是 1它会打印出 “x is 1” 和 “x is 2”因为 fallthrough 语句导致程序继续执行下一个 case
switch 也支持不带表达式的用法其中每个 case 可以包含一个条件表达式
y : 20switch {
case y 10:fmt.Println(y is greater than 10)
case y 10:fmt.Println(y is exactly 10)
default:fmt.Println(y is less than 10)
}在这种情况下switch 语句类似于一系列的 if-else 语句但其语法更加清晰
switch 也可以包含初始化语句类似于 if 语句
switch z : computeValue(); {
case z 10:fmt.Println(z is greater than 10)
case z 10:fmt.Println(z is exactly 10)
default:fmt.Println(z is less than 10)
}常见用法
类型判断: switch 可以用来进行类型判断在这种情况下它会匹配一个接口变量的动态类型
var i interface{} /* 一个值 */switch t : i.(type) {
case string:fmt.Println(i is a string:, t)
case int:fmt.Println(i is an int:, t)
default:fmt.Printf(Unknown type %T\n, t)
}在这个例子中i.(type) 用来发现接口变量 i 的动态类型 注意i.(type) 用于 switch 语句中进行类型断言的类型判断。它只能在 switch 的类型判断分支中使用不可以单独使用在其他地方
多值匹配: 你可以在一个 case 语句中测试多个值。这可以简化代码避免编写多个具有相同结果的 case 语句
switch x {
case 1, 2, 3:fmt.Println(x is 1, 2 or 3)
default:fmt.Println(x is not 1, 2, or 3)
}条件组合: case 语句中可以包含多个条件这些条件可以是逻辑表达式
switch {
case x 0 x 10:fmt.Println(x is between 1 and 9)
case x 10 || x 20:fmt.Println(x is either 10 or 20)
}无条件的 switch: 无条件的 switch 相当于一个更优雅的 if-else 链
switch {
case score 90:fmt.Println(Grade: A)
case score 80:fmt.Println(Grade: B)
case score 70:fmt.Println(Grade: C)
default:fmt.Println(Grade: F)
}退出循环: 在循环内部switch 可以与 break 语句一起使用来退出循环
for {switch {case someCondition():fmt.Println(Condition met)break // 默认只会跳出 switchdefault:fmt.Println(Default case)}break // 退出 for 循环
}请注意在这种情况下break 语句只会退出 switch而不是循环。要退出循环需要在外部再次使用 break 语句
跳过当前迭代: 在循环中使用 switch可以配合 continue 语句来跳过当前迭代
for x : 0; x 5; x {switch {case x%2 0:// 跳过偶数continue}fmt.Println(Odd:, x)
}