golang中select和switch的区别

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")
}
复制代码

 

posted @   Mr.peter  阅读(279)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
历史上的今天:
2021-03-25 Couldn't open file /mnt/iso/repodata/repomd.xml
2021-03-25 dos2unix批量转换命令
2019-03-25 Linux操作系统加固
2019-03-25 MySQL服务安全加固
2019-03-25 PHP环境安全加固
2019-03-25 Tomcat服务安全加固
2019-03-25 网站被植入Webshell的解决方案
点击右上角即可分享
微信分享提示