基础语法:
第一种:有表达式
switch 表达式{
case 值1,值2: //case后的条件可以是多个值
执行语句1
case 值3:
执行语句2
......
default: //若以上条件都不满足,则执行下面的语句
执行语句n
}
第二种:无表达式
switch {
case 条件1:
执行语句1
case 条件2:
执行语句2
......
default: //若以上条件都不满足,则执行下面的语句
执行语句n
}
注意:
1.多个case和default只能执行一个
2.case中添加fallthrough可以执行下一条case
案例:
func main() {
i := 2
fmt.Print("Write ", i , " as ")
switch i {
case 1:
fmt.Println("one")
case 2:
fmt.Println("two")
case 3:
fmt.Println("three")
}
switch time.Now().Weekday() {
case time.Saturday, time.Sunday:
fmt.Println("It's the weekend")
default:
fmt.Println("It's the weekday")
}
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("It's 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 an int")
default:
fmt.Printf("Don't know type %T\n", t)
}
}
whatAmI(true)
whatAmI(123)
whatAmI("sdf")
}
Output:
Write 2 as two
It's the weekday
It's after noon
I'm a bool
I'm an int
Don't know type string