Go by Example

Non-Blocking Channel Operations

Use select with a default case to attempt a channel send or receive without blocking.

A channel passes values between goroutines, function calls started with go that can run while their caller continues. The select statement can send or receive on channels. With a default case, it immediately runs default if no channel operation can continue. This is useful when the program should do something else instead of waiting.

The send succeeds only if the one-slot buffer has room. The receive succeeds only if a value is ready.

package main
 
import "fmt"
 
func main() {
    messages := make(chan string, 1)
    select {
    case messages <- "event":
        fmt.Println("sent")
    default:
        fmt.Println("buffer full")
    }
    select {
    case message := <-messages:
        fmt.Println("received:", message)
    default:
        fmt.Println("no message")
    }
}

In production

A non-blocking send can skip an event when no receiver is ready. Count skipped events so you can see when they happen. For work that must not be lost, use a queue with a limit and make senders wait or report an error when it is full.

Enjoyed this? Get more software craft delivered to your inbox.