liveBook · Manning

Default case

As explained in 100 Go Mistakes and How to Avoid Them

A default case is a select or switch clause chosen when no other eligible case can be selected.

A default case in a Go select is chosen only when no other case is ready. It makes the select nonblocking, rather than waiting for a channel operation. section 9.4

A common mistake is treating select cases as source-ordered. When several channel operations are ready, Go chooses among them randomly; default does not automatically lose by appearing later. section 9.4

Drain remaining messages after disconnection

After receiving from disconnectCh, an inner select can repeatedly receive from messageCh. It handles every currently available message, then takes default and returns when messageCh has none ready. Messages sent after the goroutine returns can still be missed. section 9.4

for {
    select {
    case v := <-messageCh:
        fmt.Println(v)
    case <-disconnectCh:
        for {                          #1
            select {
            case v := <-messageCh:     #2
                fmt.Println(v)
            default:                   #3
                fmt.Println("disconnection, return")
                return
            }
        }
    }
}

The nested select shows the practical pattern: receive available messages through the channel case, then use default to stop without blocking. section 9.4

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains selection semantics, nested draining, nondeterministic readiness, and the boundary where later messages are missed.
Examples
Uses messageCh and disconnectCh to trace disconnection handling, remaining-message delivery, and default-case return.
What it assumes
Assumes familiarity with Go channels and select, while clarifying readiness, random choice, and nonblocking default behavior.
What you can do after
Apply nested select logic to consume ready messages and terminate without blocking when a channel is temporarily empty.
How it connects
Connects default cases with select, channels, goroutines, disconnection signals, and producer race conditions.

Also explained in

Compare how 2 books explain default case →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.