利用select非阻塞接收数据

您可以使用select语句的default部分来实现非阻塞等待。
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan int, 1)
end:
for {
select {
case n := <-ch:
fmt.Printf("Received %d from a channel\n", n)
break end
default:
fmt.Print("Channel is empty\n")
ch <- 8
}
// wait for channel to be filled with values
// don't use time.Sleep() like that in production code
time.Sleep(20 * time.Millisecond)
}
}
----------Output------------
Channel is empty
Received 8 from a channel
在第一遍for循环迭代中,select语句在执行到default子句时就立即结束,因为通道是空的。
第一遍的default子句中将8发送到了通道,第二遍迭代时case子句命中,然后将数据取出并中断循环。