19、交换器 switch

你可能对switch有这样的印象。

它有case和break语句,除非有失败的语句结束。

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "runtime"
 6 )
 7 
 8 func main() {
 9     fmt.Print("Go runs on ")
10     switch os := runtime.GOOS; os {
11     case "darwin":
12         fmt.Println("OS X.")
13     case "linux":
14         fmt.Println("Linux.")
15     default:
16         // freebsd, openbsd,
17         // plan9, windows...
18         fmt.Printf("%s.", os)
19     }
20 }
Go runs on Linux.
switch 从上到下评估一个case,直到找到一个匹配的case,才停止。
 1 package main
 2 
 3 import (
 4     "fmt"
 5     "time"
 6 )
 7 
 8 func main() {
 9     fmt.Println("When's Saturday?")
10     today := time.Now().Weekday()
11     switch time.Saturday {
12     case today+0:
13         fmt.Println("Today.")
14     case today+1:
15         fmt.Println("Tomorrow.")
16     case today+2:
17         fmt.Println("In two days.")
18     default:
19         fmt.Println("Too far away.")
20     }
21 }
When's Saturday?
Too far away.

Switch没有条件语句等同于Switch true.
这样的结构可以更清晰的表达一个长的if then else 链式语句 。
package main

import (
    "fmt"
    "time"
)

func main() {
    t := time.Now()
    switch {
    case t.Hour() < 12:
        fmt.Println("Good morning!")
    case t.Hour() < 17:
        fmt.Println("Good afternoon.")
    default:
        fmt.Println("Good evening.")
    }
}
Good evening.

你可能感兴趣的:(19、交换器 switch)