switch 语句
自动 break 的 switch、无表达式 switch、type switch、fallthrough
switch 语句
Go 的 switch 比 C/Java 更强大:不需要 break(自动终止)、可以用表达式、可以匹配类型。
学完本章你将: 掌握无 break switch、无表达式 switch、type switch、fallthrough。
基本 switch
go
package main
import "fmt"
func main() {
day := 3
switch day {
case 1:
fmt.Println("周一")
case 2:
fmt.Println("周二")
case 3:
fmt.Println("周三") // 自动 break,不会穿透
default:
fmt.Println("其他")
}
}
无表达式 switch = 更优雅的 if-else
go
score := 85
switch { // 没有表达式,case 里写条件
case score >= 90:
fmt.Println("A")
case score >= 80:
fmt.Println("B")
case score >= 60:
fmt.Println("C")
default:
fmt.Println("D")
}
type switch —— 判断接口类型
go
func describe(v interface{}) {
switch v := v.(type) {
case int:
fmt.Printf("整数:%d\n", v)
case string:
fmt.Printf("字符串:%s\n", v)
case bool:
fmt.Printf("布尔:%t\n", v)
default:
fmt.Printf("其他类型:%T\n", v)
}
}
fallthrough —— 有意穿透
go
switch n := 2; n {
case 1:
fmt.Println("一")
fallthrough // 继续执行下一个 case(不管是否匹配)
case 2:
fmt.Println("二")
fallthrough
case 3:
fmt.Println("三")
}
// 输出:二 三