No.1 Select:
select只能用于channel的操作,發(fā)送或接受數(shù)據(jù),如果select有多個(gè)分支滿足條件,他的特點(diǎn)是->隨機(jī)選取其中一個(gè)滿足條件的分支戏羽。
官方解釋如下:
If multiple cases can proceed, a uniform pseudo-random choice is made to decide which single communication will execute.
下面是Concrete Example:
package main
import (
"fmt"
"time"
)
func main() {
c1 := make(chan string)
c2 := make(chan string)
go func() {
time.Sleep(time.Second * 1)
c1 <- "one"
}()
go func() {
time.Sleep(time.Second * 1)
c2 <- "two"
}()
select {
case msg1 := <-c1:
fmt.Println("msg1 received is:", msg1)
case msg2 := <-c2:
fmt.Println("msg2 received is:", msg2)
}
}
雖然代碼中select中2個(gè)分支的條件都是滿足的,但是他不像switch那樣按順序楼吃。大家可以吧代碼復(fù)制了自己測試下始花。
下面來看看我自己測試個(gè)6個(gè)結(jié)果:
msg1 received is: one
msg2 received is: two
msg2 received is: two
msg1 received is: one
msg2 received is: two
msg1 received is: one
No.2 Switch:
switch分支是按順序執(zhí)行的,這點(diǎn)和select不同孩锡,可以為各種類型進(jìn)行分支操作這一點(diǎn)又與select不同衙荐,還可以用來判斷類型。
下面是Concrete Example:
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")
}
switch time.Now().Weekday() {
case time.Saturday, time.Sunday:
fmt.Println("It's the weekend")
default:
fmt.Println("It's a weekday")
}
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("It's before noon")
default:
fmt.Println("It's after noon")
}
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")
}
下面的輸出結(jié)果一目了然我不多解釋:
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