2 回答
TA贡献1934条经验 获得超2个赞
它是保证非阻塞发送到通道的方法。如果 c.send chan 现在不能接受新消息,将执行一个默认分支。如果没有 select{} 块发送到未缓冲或完全填充的缓冲通道,则可以被阻止。
TA贡献1796条经验 获得超4个赞
https://gobyexample.com/non-blocking-channel-operations
// Basic sends and receives on channels are blocking.
// However, we can use `select` with a `default` clause to
// implement _non-blocking_ sends, receives, and even
// non-blocking multi-way `select`s.
package main
import "fmt"
func main() {
messages := make(chan string)
//[...]
// Here's a non-blocking receive. If a value is
// available on `messages` then `select` will take
// the `<-messages` `case` with that value. If not
// it will immediately take the `default` case.
select {
case msg := <-messages:
fmt.Println("received message", msg)
default:
fmt.Println("no message received")
}
// A non-blocking send works similarly.
msg := "hi"
select {
case messages <- msg:
fmt.Println("sent message", msg)
default:
fmt.Println("no message sent")
}
//[...]
}
更明确地说:对于非阻塞“发送”,case如果有接收者已经在等待消息,则第一个将发生。否则它会回落到default
- 2 回答
- 0 关注
- 170 浏览
添加回答
举报