Understand the contract

select waits until a channel send or receive can proceed, then executes one ready case. If several cases are ready, one is chosen pseudo-randomly; source order does not establish priority. Use it to coordinate input, output and cancellation without polling each channel in a tight loop.

A default branch runs immediately when no communication can proceed. That is useful for a deliberate nonblocking attempt, but adding default to an otherwise blocking loop can make it spin and consume CPU. A closed cancellation channel is always ready to receive from, providing a broadcast signal.

Work through the example

The example chooses between work and a done channel. With one buffered job and done still open, it prints the job. If you close done before select, both cases may be ready and either outcome is valid. Cancellation does not promise priority over already-ready work.

package main

import "fmt"

func main() {
    jobs := make(chan string, 1)
    done := make(chan struct{})
    jobs <- "compile"
    select {
    case job := <-jobs:
        fmt.Println(job)
    case <-done:
        fmt.Println("cancelled")
    }
}

Watch this boundary

A receive from a closed data channel stays ready and returns zero values. In a loop, check ok and return or disable that case by assigning its channel variable to nil. Otherwise the loop can repeatedly process nonexistent data and consume CPU after the producer finishes.

Practice with a changed input

Close done before selecting and run the program repeatedly without asserting a fixed winner. Then write a loop that exits cleanly when its work channel is closed.

References & further reading

Need help with your Go backend?

I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.

Explore Go consulting services