点击(此处)折叠或打开

  1. // Switch
  2. package main

  3. import (
  4.     "fmt"
  5.     "time"
  6. )

  7. func main() {
  8.     //Here’s a basic switch.
  9.     i := 2
  10.     fmt.Print("write ", i, " as ")
  11.     switch i {
  12.     case 1:
  13.         fmt.Println("one")
  14.     case 2:
  15.         fmt.Println("two")
  16.     case 3:
  17.         fmt.Println("three")
  18.     }
  19.     //You can use commas to separate multiple expressions in the same case statement.
  20.     //We use the optional default case in this example as well.
  21.     switch time.Now().Weekday() {
  22.     case time.Saturday, time.Sunday:
  23.         fmt.Println("it's the weekend")
  24.     default:
  25.         fmt.Println("it's a weekday")
  26.     }
  27.     //switch without an expression is an alternate way to express if/else logic.
  28.     //Here we also show how the case expressions can be non-constants.
  29.     t := time.Now()
  30.     switch {
  31.     case t.Hour() < 12:
  32.         fmt.Println("it's before noon")
  33.     default:
  34.         fmt.Println("it's after noon")
  35.     }
  36. }
转自https://gobyexample.com
09-06 17:24