golang的switch语句可以表达多个分支条件
package main
import (
"fmt"
"time"
)
func main() {
i := 2
fmt.Print("Write ", i, " as ")
// 基本的switch
switch i {
case 1:
fmt.Println("one")
case 2:
fmt.Println("two")
case 3:
fmt.Println("three")
}
// 在同一个case中,可以用逗号分割多个表达式。default是可选的
switch time.Now().Weekday() {
case time.Saturday, time.Sunday:
fmt.Println("It's the weekend")
default:
fmt.Println("It's a weekday")
}
// 没有表达式的switch是另一种if/else逻辑判断。
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("It's a before noon")
default:
fmt.Println("It's after noon")
}
whatAmI := func(i interface{}) {
switch t := i.(type) {
case bool:
fmt.Println("I'm a bool")
case int:
fmt.Println("I'm a int")
default:
fmt.Printf("Don't know type %T\n", t)
}
}
whatAmI(true)
whatAmI(1)
whatAmI("hey")
}
// print
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm a int
Don't know type string
本文详细介绍了Go语言中的switch语句,包括基本用法、在同一case中处理多个表达式、以及使用interface进行类型判断。通过实例展示了如何利用switch实现不同类型的逻辑判断。

被折叠的 条评论
为什么被折叠?



