switch 多分支语句可以简化大量的判断(相对于 if 语句)
var n = 3
switch n {
case 1:
fmt.Println("大拇指")
case 2:
fmt.Println("食指")
case 3:
fmt.Println("中指")
case 4:
fmt.Println("无名指")
case 5:
fmt.Println("小拇指")
default:
fmt.Println("无效数字")
}
输出
中指
Go 语言的 switch 语句默认仅执行第一个匹配的分支, 而不会继续执行下面的分支
case 分支中可以放置多个值, 只要其中一个匹配了就算匹配
var n = 3
switch n {
case 1, 3, 5, 7, 9:
fmt.Println("奇数")
case 0, 2, 4, 6, 8:
fmt.Println("偶数")
default:
fmt.Println(n)
}
打印
奇数
还可以在 case 中使用表达式, 表达式为真时表示该分支成功匹配
age := 19
switch {
case age < 18:
fmt.Println("未成年")
case age >= 18:
fmt.Println("已成年")
}
打印
已成年
为了兼容其他语言, Go 添加了 fallthrough 关键字, 在分支的末尾使用, 表示匹配成功后继续执行下一个分支
switch {
case true:
fmt.Println(1)
fallthrough
case false:
fmt.Println(2)
fallthrough
case false:
fmt.Println(3)
// 最后一个分支不可使用 fallthrough(不能再往下执行了)
default:
fmt.Println(0)
}
打印
1
2
3
匹配第1个分支后, 由于其末尾有 fallthrough, 因此继续执行第2个分支, 同理第2个分支也有 fallthrough, 继续执行第3个分支, 然后退出