golang中select和switch的區別
阿新 • • 發佈:2022-03-25
select
select
只能應用於channel的操作,既可以用於channel的資料接收,也可以用於channel的資料傳送。
如果select
的多個分支都滿足條件,則會隨機的選取其中一個滿足條件的分支, 如語言規範中所說:
If multiple cases can proceed, a uniform pseudo-random choice is made to decide which single communication will execute.
`case`語句的表示式可以為一個變數或者兩個變數賦值。
有default
語句。
package main
import "time"
import "fmt"
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 * 2)
c2 <- "two"
}()
for i := 0; i < 2; i++ {
select {
case msg1 := <-c1:
fmt.Println("received", msg1)
case msg2 := <-c2:
fmt.Println("received", msg2)
}
}
}
switch
switch
可以為各種型別進行分支操作, 設定可以為介面型別進行分支判斷(通過i.(type))。
switch
分支是順序執行的,這和select
不同。
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") }