Go switch 语句
switch 语句
使用 switch 语句可以选择多个代码块之一来执行。
Go 中的 switch 语句与 C、C++、Java、JavaScript 和 PHP 中的类似。不同的是,它只会运行匹配的 case,因此不需要 break 语句。
单个 case 的 switch 语法
语法
switch 表达式 {
case x:
// 代码块
case y:
// 代码块
case z:
...
default:
// 代码块
}
这是它的工作方式:
- 表达式被评估一次
- 将
switch表达式的值与每个case的值进行比较 - 如果有匹配,则执行相关的代码块
default关键字是可选的。如果没有匹配的case,它会指定一些要运行的代码
单个 case 的 switch 实例
下面的例子使用一周中的 weekday 编号来计算一周中的 weekday 名称:
实例
package main
import ("fmt")
func main() {
day := 4
switch day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
case 4:
fmt.Println("Thursday")
case 5:
fmt.Println("Friday")
case 6:
fmt.Println("Saturday")
case 7:
fmt.Println("Sunday")
}
}
结果:
Thursday
default 关键字
default 关键字指定在没有 case 匹配时要运行的一些代码:
实例
package main
import ("fmt")
func main() {
day := 8
switch day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
case 4:
fmt.Println("Thursday")
case 5:
fmt.Println("Friday")
case 6:
fmt.Println("Saturday")
case 7:
fmt.Println("Sunday")
default:
fmt.Println("Not a weekday")
}
}
结果:
Not a weekday
所有 case 的值应该与 switch 表达式的类型相同。否则,编译器会报错:
实例
package main
import ("fmt")
func main() {
a := 3
switch a {
case 1:
fmt.Println("a is one")
case "b":
fmt.Println("a is b")
}
}
结果:
./prog.go:11:2: cannot use "b" (type untyped string) as type int (无法将 "b"(无类型字符串)用作 int 类型)
多分支 switch 语句
在 switch 语句中,每个 case 可以有多个值:
语法
switch 表达式 {
case x, y:
// 如果表达式的值为 x 或 y,则执行此代码块
case v, w:
// 如果表达式的值为 v 或 w,则执行此代码块
case z:
...
default:
// 如果表达式的值不在任何 case 中,则执行此代码块
}
多分支 switch 示例
下面的示例使用工作日编号来返回不同的文本:
实例
package main
import ("fmt")
func main() {
day := 5
switch day {
case 1,3,5:
fmt.Println("奇数工作日")
case 2,4:
fmt.Println("偶数工作日")
case 6,7:
fmt.Println("周末")
default:
fmt.Println("无效的工作日编号")
}
}
结果:
奇数工作日