在线文档  >   Golang练习   >   Switch 分支结构

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

运行结果如下:

$ go run switch.go 
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type string