(この記事は Go by Example: Switch を翻訳したものです。)
switchは枝がたくさんある条件分岐を表現します。
package main
import "fmt"
import "time"
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")
}
// 一つの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")
}
}
$ go run switch.go
write 2 as two
it's the weekend
it's before noon