select statement

The select statement lets a Go goroutine wait for multiple channel send or receive operations and executes one case whose communication can proceed. A default case makes the select non-blocking, while a case receiving from ctx.Done() provides a way to respond to context cancellation.

Minimal example

go
select {
case message := <-messages:
    fmt.Println(message)
case <-ctx.Done():
    return
default:
    return
}

Learn this concept

Lesson 5.1 · Channels, select and cleanup

Used in exercises

Exercise 5.3 · Per-user WebSocket hub
Prerequisite conceptsChannelsGo context