select

select waits on several channels at once. default makes waiting optional, and an empty default easily becomes a hot loop.

select chooses one ready channel:

select {
case v := <-jobs:
    handle(v)
case <-ctx.Done():
    return ctx.Err()
case <-time.After(time.Second):
    return errors.New("timeout")
}

If several branches are ready, a random one is chosen. Do not rely on the order of case. default fires when no channel is ready, and then select does not block. In a loop a bare default with no pause spins the processor. For a poll "is there a message" it is appropriate once, not as an eternal loop.

time.After is convenient in one select and bad in a high-frequency loop: every call creates a timer. For a repeating tick there is time.NewTicker, and it is stopped with defer ticker.Stop().

Cancellation through a context is an ordinary select branch, not separate magic. The channel ctx.Done() is closed when the context is canceled or the deadline has passed. A function that waits only on its work channel and does not look at Done is not canceled. A context does not itself interrupt code in the middle of arithmetic. You have to read it.

Do not nest select in select without a need. If there are five branches and they hold domain logic, spread the handlers into functions and leave only the choice of source in the select.

Practice

  1. Several ready branches

    In a select, two case branches are ready at once. Which one runs?

    • The one written higher
    • A random one among the ready ones
    • Both, from top to bottom
    • Neither. There will be a panic
  2. default in a loop

    What is dangerous about an infinite loop with select and a default branch, if the channels are often empty?

    • The compiler will delete default
    • The goroutine will occupy the processor with no benefit
    • default automatically waits a millisecond
    • The channel will close itself
  3. Where to look at cancellation

    A function computes for a long time in a loop and never reads ctx.Done(). Will canceling the context stop this loop by itself? Write yes or no.