Switch {.en}

Switch 语句 {.zh}

::: {.en} Switch statements express conditionals across many branches. :::

::: {.zh}

Switch 语句用于多个分支的条件。

:::

  1. package main
  2. import "fmt"
  3. import "time"
  4. func main() {

::: {.en} Here’s a basic switch. :::

::: {.zh}

一个基本的 switch

:::

  1. i := 2
  2. fmt.Print("Write ", i, " as ")
  3. switch i {
  4. case 1:
  5. fmt.Println("one")
  6. case 2:
  7. fmt.Println("two")
  8. case 3:
  9. fmt.Println("three")
  10. }

::: {.en} You can use commas to separate multiple expressions in the same case statement. We use the optional default case in this example as well. :::

::: {.zh}

您可以使用逗号分隔同一 case 语句中的多个表达式。我们在这个例子中也使用了可选的 default 分支。

:::

  1. switch time.Now().Weekday() {
  2. case time.Saturday, time.Sunday:
  3. fmt.Println("It's the weekend")
  4. default:
  5. fmt.Println("It's a weekday")
  6. }

::: {.en} switch without an expression is an alternate way to express if/else logic. Here we also show how the case expressions can be non-constants. :::

::: {.zh}

没有表达式的 switch 是表达 if / else 逻辑的另一种方式。这里我们还展示了 case 表达式也可以不使用常量。

:::

  1. t := time.Now()
  2. switch {
  3. case t.Hour() < 12:
  4. fmt.Println("It's before noon")
  5. default:
  6. fmt.Println("It's after noon")
  7. }

::: {.en} A type switch compares types instead of values. You can use this to discover the type of an interface value. In this example, the variable t will have the type corresponding to its clause. :::

::: {.zh}

类型开关(type switch) 比较类型而非值。可以使用它来发现接口值的类型。在这个例子中,变量 t 在每个分支中会有相应的类型。

:::

  1. whatAmI := func(i interface{}) {
  2. switch t := i.(type) {
  3. case bool:
  4. fmt.Println("I'm a bool")
  5. case int:
  6. fmt.Println("I'm an int")
  7. default:
  8. fmt.Printf("Don't know type %Tn", t)
  9. }
  10. }
  11. whatAmI(true)
  12. whatAmI(1)
  13. whatAmI("hey")
  14. }
  1. $ go run switch.go
  2. Write 2 as two
  3. It's a weekday
  4. It's after noon
  5. I'm a bool
  6. I'm an int
  7. Don't know type string