Go Reference ยท Keywords and Statements
The select statement
Reference for Go select: waiting on several channel sends and receives, the default case, timeouts with time.After, nil channels and random choice.
select waits on several channel operations at once and runs the case whose operation can proceed. It looks like a switch, but each case is a channel send or receive. If several are ready, Go picks one at random; if none is ready, select blocks until one is, or runs the default case when there is one.
It is the tool for timeouts, cancellation, fan-in from many channels and non-blocking channel operations.
select { case msg := <-ch: fmt.Println(msg) case <-time.After(time.Second): fmt.Println("timeout") }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
select { case v := <-ch1: case v, ok := <-ch2: case ch3 <- value: case <-done: default: }
| Part | Description |
|---|---|
| receive case | <-ch, optionally assigned with = or :=, optionally with ok. Ready when a value is available or the channel is closed. |
| send case | ch <- v. Ready when a receiver is waiting or the buffer has space. |
default |
Runs immediately when no other case is ready. Makes the select non-blocking. |
Errors and edge cases:
- Channel expressions and send values of all cases are evaluated once, in source order, before anything is chosen.
- A
nilchannel is never ready, which lets you switch a case off by setting the variable tonil. - A
select {}with no cases blocks forever. If every goroutine is asleep, the runtime reportsfatal error: all goroutines are asleep - deadlock!. - Sending on a closed channel in a send case panics when that case is chosen.
breakinside a case leaves theselect, not an enclosingfor.
Usage notes
- Random choice prevents starvation but means you cannot rely on case order for priority. For priority, nest a non-blocking
selectfirst. - Timeouts:
time.Afteris simple but allocates a timer per call; in tight loops reuse atime.Timeror usecontext.WithTimeoutand actx.Done()case. - Cancellation:
case <-ctx.Done():is the standard exit in worker loops. - Loop plus select is the usual shape:
for { select { ... } }. Remember toreturnor use a labeledbreakto exit. - Disabling cases: set a channel variable to
nilafter it closes so the loop stops spinning on it. - A
defaultbranch in a loop turns it into a busy-wait. Add a blocking case or sleep instead. - Fan-in merges several channels into one by forwarding from each in a goroutine, or with one
selectfor a fixed number.