4

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


LiberHome
409 声望1.1k 粉丝

有问题 欢迎发邮件 📩 liberhome@163.com