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.

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
selectevaluates all case expressions, then blocks until one communication can proceed; if several can, one is chosen at random.defaultruns when no other case is ready, turning the statement into a non-blocking poll; putting it in a loop creates a busy loop.- A
nilchannel 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.Afterinside a loop allocates a timer per iteration; a reusedtime.TimerwithResetis the lower-allocation form.breakinside aselectleaves theselect, not the enclosingfor; 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 reportsall goroutines are asleep - deadlock!.
Basic syntax and type signatures
select {
case v := <-in:
use(v)
case out <- v:
sent()
case <-done:
return
case <-time.After(100 * time.Millisecond):
timedOut()
default:
nothingReady()
}// 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
| Case | nil channel | open, empty | open, full or receiver waiting | closed |
|---|---|---|---|---|
case v := <-ch | never ready | ready when a value is queued or a sender waits | ready | always ready, zero value |
case ch <- v | never ready | ready when a receiver waits | ready when space | panics if chosen |
case <-done | never ready | blocks | ready | always ready |
default | runs when nothing else is ready | same | same | same |
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
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
// 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
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
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
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 symptom | Cause | Fix |
|---|---|---|
fatal error: all goroutines are asleep - deadlock! | select with no ready case and no other runnable goroutine | check that every case can fire; add a timeout |
| CPU at 100% while idle | default inside a loop | remove default, or add a sleep/ticker |
| A case never runs | its channel is nil | assign the channel, or remove the case |
| A closed channel's case runs forever | no ok check | return, or set the channel to nil |
panic: send on closed channel | a send case selected after close | close only from the owner after senders finish |
| Timeout fires twice | timer.Reset without draining | stop and drain before reset |
| Memory grows in a polling loop | time.After per iteration | reuse a time.Timer |
Loop never exits on break | break inside select | labeled break |
| Cancellation ignored during a send | send not inside a select with ctx.Done() | wrap the send |
| Results lost at shutdown | result channel closed before senders finish | close 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 toolsSmall utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Go guides
All Go guidesGo iota: Enumerations, Bitmask Flags, and Constant Expressions
How iota advances per const line, typed enums with gaps, bit flags with 1 << iota, and the unit scale pattern that shifts with one blank line.
Go JSON: Marshaling, Unmarshaling, Struct Tags, and Custom Parsers
Struct tags, omitempty that skips false and zero, custom marshalers without recursion, RawMessage for tagged unions, and float64 precision loss.
Go Strings, Runes, and Bytes: UTF-8 Encoding, Conversion, and Memory
Bytes versus runes, len that counts bytes, slicing that splits characters, Builder for linear concatenation, and normalization the standard library omits.
Go init Function: Package Initialization Order, Imports, and Side Effects
What runs before main, the order across imports and files, why init cannot return an error, and the sync.Once replacement that can be tested.
More in Go
All Go guidesThe guides filed next to this one in Go, in library order.