select与switch的区别

No.1 Select:

select只能用于channel的操作,发送或接受数据,如果select有多个分支满足条件,他的特点是->随机选取其中一个满足条件的分支。

官方解释如下:
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个分支的条件都是满足的,但是他不像switch那样按顺序。大家可以吧代码复制了自己测试下。

下面来看看我自己测试个6个结果:
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分支是按顺序执行的,这点和select不同,可以为各种类型进行分支操作这一点又与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")
}
下面的输出结果一目了然我不多解释:
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

你可能感兴趣的:(select与switch的区别)