select is a select statement provided by Go. Through select, you can monitor the data flow on the channel.
The use of the select statement is similar to that of the switch statement. A new selection block is started by select, and each selection block and each selection condition are implemented by a case statement.
The difference from the switch statement is that the case conditions of select are all channel communication operations, and the select statement may be blocked or executed according to different cases.
for example:
package main
import (
"fmt"
"time"
)
func main() {
ch1 := make(chan int)
ch2 := make(chan int)
go func() {
time.Sleep(3 * time.Second)
ch1 <- 100
}()
go func() {
time.Sleep(3 * time.Second)
ch2 <- 100
}()
select {
case num1 := <-ch1:
fmt.Println("ch1中获取的数据: ", num1)
case num2, ok := <-ch2:
if ok {
fmt.Println("ch2中读取的数据: ", num2)
} else {
fmt.Println("ch2 已关闭")
}
//default:
// fmt.Println("default语句可选 可有可无")
}
fmt.Println("main goroutine has been completed")
}
Here, since both ch1 and ch2 have written data, select will randomly select a case to execute. If there is a default statement, it will execute the default statement. If there is none, it will block until a case that meets the conditions appears.
Reference: bilibili
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。