Golang - switch和select的异同点

select与switch的区别:

1:每个switch后面必须跟随一个条件判断,而select后面没有

2:switch中的case语句为枚举值进行比较,select中的case必须是一个对channel的读或者写的操作

select与switch的相同点:

如果switch或select中的case都不成功,那么都会进入default

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子句总是可运行的,所以没有default的select才会阻塞等待事件;没有运行的case,那将会阻塞事件发生报错(死锁)。

复制代码

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 * 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随机选取有所不同。

default语句可以放在任何位置,也可以省略。

case后面可以带多个值,使用逗号间隔即可。

case后面不需要break。

switch穿透,利用fallthrough关键字,如果在case语句块后增加fallthrough,则会继续执行下一个case,也就是说会执行当前case和下一个case。

复制代码
package main
import (
"fmt"
"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 @   李若盛开  阅读(449)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
点击右上角即可分享
微信分享提示