在 Go 选择语句模型 如下:
switch expression {
case expression 1:
code
case expression 2:
code
case expression 3:
code
case expression ...:
code
default:
code
}
switch
语句是一个选择语句,用于将 switch
后的表达式的值与可能匹配的选项 case
后的表达式进行比较,并根据匹配情况执行相应的代码块,执行完匹配的代码块后,直接退出 switch-case
。如果没有任何一个匹配,就会执行 default
的代码块。它可以被认为是替代多个 if-else
子句的常用方式。注意:case
不允许出现重复项。例如,下面的例子会输出 Your score is between 80 and 90.
。
grade := "B"
switch grade {
case "A":
fmt.Println("Your score is between 90 and 100.")
case "B":
fmt.Println("Your score is between 80 and 90.")
case "C":
fmt.Println("Your score is between 70 and 80.")
case "D":
fmt.Println("Your score is between 60 and 70.")
default:
fmt.Println("Your score is below 60.")
}
一个 case 多个条件
在 Go 中, case
后可以接多个条件,多个条件之间是 或 的关系,用逗号 ,
相隔。
month := 5
switch month {
case 1, 3, 5, 7, 8, 10, 12:
fmt.Println("该月份有 31 天")
case 4, 6, 9, 11:
fmt.Println("该月份有 30 天")
case 2:
fmt.Println("该月份闰年为 29 天,非闰年为 28 天")
default:
fmt.Println("输入有误!")
}
选择语句另一种写法
switch
还有另外一种写法,它包含一个 statement
可选语句部分,该可选语句在表达式之前运行。它的语法是:
switch statement; expression {
}
可以将上面的例子改写为:
switch month := 5; month {
case 1, 3, 5, 7, 8, 10, 12:
fmt.Println("该月份有 31 天")
case 4, 6, 9, 11:
fmt.Println("该月份有 30 天")
case 2:
fmt.Println("该月份闰年为 29 天,非闰年为 28 天")
default:
fmt.Println("输入有误!")
}
这里 month
变量的作用域就仅限于这个 switch
内。
switch 后可接函数
switch
后面可以接一个函数,只要保证 case
后的值类型与函数的返回值一致即可。
package main
import "fmt"
func getResult(args ...int) bool {
for _, v := range args {
if v < 60 {
return false
}
}
return true
}
func main() {
chinese := 88
math := 90
english := 95
switch getResult(chinese, math, english) {
case true:
fmt.Println("Pass all exams")
case false:
fmt.Println("Part of the exam failed")
}
}
无表达式的 switch
switch
后面的表达式是可选的。如果省略该表达式,则表示这个 switch
语句等同于 switch true
,并且每个 case
表达式都被认定为有效,相应的代码块也会被执行。
score := 88
switch {
case score >= 90 && score <= 100:
fmt.Println("grade A")
case score >= 80 && score < 90:
fmt.Println("grade B")
case score >= 70 && score < 80:
fmt.Println("grade C")
case score >= 60 && score < 70:
fmt.Println("grade D")
case score < 60:
fmt.Println("grade E")
}
该 switch-case
语句相当于 if-elseif-else
语句。
fallthrough 语句
正常情况下 switch-case
语句在执行时只要有一个 case
满足条件,就会直接退出 switch-case
,如果一个都没有满足,才会执行 default
的代码块。不同于其他语言需要在每个 case
中添加 break
语句才能退出。使用 fallthrough
语句可以在已经执行完成的 case
之后,把控制权转移到下一个 case
的执行代码中。fallthrough
只能穿透一层,不管你有没有匹配上,都要退出了。fallthrough
语句是 case
子句的最后一个语句。如果它出现在了 case
语句的中间,编译会不通过。
s := "hello"
switch {
case s == "hello":
fmt.Println("hello")
fallthrough
case s == "my":
fmt.Println("my")
case s != "world":
fmt.Println("world")
}
上面的程序输出如下:
参考文献:
[1] Alan A. A. Donovan; Brian W. Kernighan, Go 程序设计语言, Translated by 李道兵, 高博, 庞向才, 金鑫鑫 and 林齐斌, 机械工业出版社, 2017.