Switch 敘述對應許多分支中的條件式。
|
|
|

package main
|
|
import (
"fmt"
"time"
)
|
|
func main() {
|
以下是基本的 switch 。
|
i := 2
fmt.Print("Write ", i, " as ")
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 邏輯的另外一種方式。在此我們也會展示 case 表達式如何可以是非常數。
|
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("It's before noon")
default:
fmt.Println("It's after noon")
}
|
類型 switch 會比較類型而非值。您可以使用這點來找出介面值是哪種類型。在此範例中,變數 t 會具有對應子句的類型。
|
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(1)
whatAmI("hey")
}
|