Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Go select Statement: Non-Blocking Operations, Timeouts, and Nil Channels

Random choice among ready cases, non-blocking polls with default, nil channels that disable a case, timer reuse, and labeled breaks out of a loop.

~5 min readGo
#Go#Concurrency#Control Flow
3D illustration of channel ports polled by a central multiplexer with a default bypass and timeout timer

select waits on several channel operations at once and runs the case that is ready. With more than one ready case it picks one pseudo-randomly, which is what makes a set of competing channels fair rather than ordered. With no ready case and no default, it blocks; with a default, it acts as a non-blocking poll. Nearly every concurrency primitive in Go — timeouts, cancellation, fan-in, worker pools, backpressure — is a select with the right cases and the right treatment of the cases that can never fire.

Quick Summary

  • select evaluates all case expressions, then blocks until one communication can proceed; if several can, one is chosen at random.
  • default runs when no other case is ready, turning the statement into a non-blocking poll; putting it in a loop creates a busy loop.
  • A nil channel in a case is never ready, which is the standard way to disable a case until a value arrives.
  • A closed channel's receive case is always ready and yields the zero value, so a closed channel needs to be removed from the loop or handled with ok.
  • time.After inside a loop allocates a timer per iteration; a reused time.Timer with Reset is the lower-allocation form.
  • break inside a select leaves the select, not the enclosing for; a labeled break is required to leave the loop.
  • Sending on a closed channel and closing a closed channel panic; receiving from a closed one is safe at any time.
  • An empty select {} blocks forever, and if no other goroutine can run, the runtime reports all goroutines are asleep - deadlock!.

Basic syntax and type signatures

go
select { case v := <-in: use(v) case out <- v: sent() case <-done: return case <-time.After(100 * time.Millisecond): timedOut() default: nothingReady() }
go
// A non-blocking receive. select { case v := <-ch: handle(v) default: // no value available: return, or do other work } // A non-blocking send: report whether it was accepted. func trySend(ch chan<- int, v int) bool { select { case ch <- v: return true default: return false } }

All the cases are evaluated first, in source order, and each case's channel expression must be ready to proceed without blocking. The receive cases may bind v and ok exactly as a normal receive does.

Case readiness by channel state

Casenil channelopen, emptyopen, full or receiver waitingclosed
case v := <-chnever readyready when a value is queued or a sender waitsreadyalways ready, zero value
case ch <- vnever readyready when a receiver waitsready when spacepanics if chosen
case <-donenever readyblocksreadyalways ready
defaultruns when nothing else is readysamesamesame

The closed row is the reason a select loop must handle ok or remove the channel: a closed channel and a cancelled context look identical to the scheduler, and both keep winning.

Practical edge cases and deep dives

1. Randomness is fairness, not a bug

go
func TestSelectFairness(t *testing.T) { a := make(chan int, 1) b := make(chan int, 1) a <- 1 b <- 2 counts := map[int]int{} for i := 0; i < 1000; i++ { select { case v := <-a: counts[v]++ a <- 1 case v := <-b: counts[v]++ b <- 2 } } if counts[1] == 0 || counts[2] == 0 { t.Fatalf("select was not fair: %v", counts) } }

When both channels have a value, select does not prefer the first case; it chooses uniformly among ready cases. That is what prevents starvation in a select over several producers, and it is also why a test that asserts "the first ready case wins" fails intermittently. The only ordering guarantee is that a case which is not ready never runs.

2. default and the busy loop

go
// Busy loop: burns a core while the channel is empty. func drainWrong(ch <-chan int) { for { select { case v := <-ch: process(v) default: // spin } } } // Correct: block when there is nothing to do. func drainRight(ch <-chan int) { for v := range ch { process(v) } } // Correct variant: do other work while waiting, with a real yield. func drainMixed(ch <-chan int, stop <-chan struct{}) { for { select { case v, ok := <-ch: if !ok { return } process(v) case <-stop: return } } }

default runs immediately whenever no communication is possible, so a for { select { ... default: } } loop never blocks and consumes a full core. It is the right tool for "try once and continue", as in trySend or a poll that does other work between attempts — not for "wait for input".

3. Timeouts without leaking timers

go
func fetch(url string) ([]byte, error) { req, _ := http.NewRequest(http.MethodGet, url, nil) select { case res := <-doRequest(req): defer res.Body.Close() return io.ReadAll(res.Body) case <-time.After(2 * time.Second): return nil, errors.New("timeout") } } // In a loop, reuse the timer instead of calling time.After every iteration. func poll(ctx context.Context, ch <-chan int) error { timer := time.NewTimer(time.Second) defer timer.Stop() for { select { case v := <-ch: handle(v) if !timer.Stop() { <-timer.C } timer.Reset(time.Second) case <-timer.C: return errors.New("idle timeout") case <-ctx.Done(): return ctx.Err() } } }

time.After creates a new timer each call, and before Go 1.23 that timer stayed reachable until it fired, so a loop calling it thousands of times held thousands of timers. Go 1.23 made unstopped timers collectable, which removes the leak but not the allocation; a reused timer with the stop-and-drain dance is still the efficient form. The if !timer.Stop() { <-timer.C } is required because a timer that fired between the select and the stop has already sent to its channel, and resetting without draining would fire twice.

4. Disabling a case with nil, and breaking the right loop

go
func merge(ctx context.Context, a, b <-chan int) []int { var out []int for a != nil || b != nil { select { case <-ctx.Done(): return out case v, ok := <-a: if !ok { a = nil // disable this case continue } out = append(out, v) case v, ok := <-b: if !ok { b = nil continue } out = append(out, v) } } return out } // break inside select leaves the select, not the for: for { select { case <-ch: break // breaks the select only: infinite loop } } // labeled break leaves the loop: loop: for { select { case <-ch: break loop } }

Setting a drained channel to nil is the cleanest way to finish a select loop over several channels: a nil case is never ready, so the loop continues on the remaining ones and ends when all are nil. The labeled break is one of the few places Go's labels earn their syntax — without it, break in a select inside a for silently does nothing to the loop.

5. Cancellation, draining, and shutdown order

go
func worker(ctx context.Context, jobs <-chan Job, results chan<- Result) { defer close(results) for { select { case <-ctx.Done(): return case job, ok := <-jobs: if !ok { return } select { case results <- process(job): case <-ctx.Done(): return } } } }

The nested select is what makes the worker cancellable while it is trying to publish a result: without it, a consumer that stopped reading blocks the worker forever. The same shape applies on the way in — a producer blocked on a full channel ignores cancellation unless its send is inside a select with ctx.Done(). Shutdown ordering follows: cancel the context, then wait for goroutines with a WaitGroup, then close the result channel once every sender is done. Anything that closes earlier produces send on closed channel under load.

Common mistakes and compiler errors

Error or symptomCauseFix
fatal error: all goroutines are asleep - deadlock!select with no ready case and no other runnable goroutinecheck that every case can fire; add a timeout
CPU at 100% while idledefault inside a loopremove default, or add a sleep/ticker
A case never runsits channel is nilassign the channel, or remove the case
A closed channel's case runs foreverno ok checkreturn, or set the channel to nil
panic: send on closed channela send case selected after closeclose only from the owner after senders finish
Timeout fires twicetimer.Reset without drainingstop and drain before reset
Memory grows in a polling looptime.After per iterationreuse a time.Timer
Loop never exits on breakbreak inside selectlabeled break
Cancellation ignored during a sendsend not inside a select with ctx.Done()wrap the send
Results lost at shutdownresult channel closed before senders finishclose after WaitGroup.Wait

The structure that avoids most of these is a single select per loop iteration with four kinds of cases: work in, cancellation, timeout, and default only if the loop is genuinely polling. Each case should either complete its work or return — a case that partially updates state and continues is where a select loop becomes hard to reason about, because the next iteration's readiness is no longer independent of what the last one did.

Try matching browser tools

All tools

Small utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Go guides

More in Go

All Go guides

The guides filed next to this one in Go, in library order.