golang中select和switch的区别
2022/3/25 23:24:54
本文主要是介绍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") }
这篇关于golang中select和switch的区别的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-04-01got an unexpected keyword argument
- 2024-03-30维多利亚的秘密 golang入坑系统
- 2024-03-29mongodb sort by date
- 2024-03-29go swagger
- 2024-03-25mongodb cdc
- 2024-03-25how to use go in vscode
- 2024-03-22mongooseserverselectionerror: connect econnrefused ::1:27017
- 2024-03-21pymongo insert_many
- 2024-03-18projection mongodb
- 2024-03-14clickhouse-go