スイッチ文では、複数の分岐にまたがる条件表現を表現します。
|
|
|

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")
}
|