Channels and Select
Nonblocking Receive
A default case lets select continue when no channel receive is ready.
Nonblocking Receive
nonblocking_receive.go
package main
import "fmt"
func main() {
var preload =
inbox := make(chan string, 1)
if preload {
inbox <- "message"
}
status := ""
select {
case value := <-inbox:
status = "received " + value
default:
status = "nothing ready"
}
fmt.Println("preload=", preload)
fmt.Println("status=", status)
fmt.Println("remaining=", len(inbox))
}
package main
import "fmt"
func main() {
var preload =
inbox := make(chan string, 1)
if preload {
inbox <- "message"
}
status := ""
select {
case value := <-inbox:
status = "received " + value
default:
status = "nothing ready"
}
fmt.Println("preload=", preload)
fmt.Println("status=", status)
fmt.Println("remaining=", len(inbox))
}
default case
A `default` case prevents a `select` from blocking when no channel operation can proceed.