select
select waits until one of several channel operations can proceed, then runs that case. If several are ready, it picks one at random. It is the switch of concurrent Go.
Detailed Explanation
You need to receive from results or from ctx.Done(), whichever happens first. A single <- can wait on only one channel. select lists several sends or receives. The runtime parks the goroutine until one case is unblocked.
Random choice among ready cases. If two channels both have a value, select does not prefer the one written first in the source. That fairness avoids starvation. If you need priority, nest: try the high-priority channel in a select with default, then wait on both.
break leaves the select, not a surrounding for. Label the loop when you need to exit both. The same trap exists with switch.
Nil cases are ignored. A nil channel in a case never becomes ready. You can disable a case by setting that channel variable to nil, which is a useful way to stop listening after a close without removing the select.
Empty select {} blocks forever. It is a way to park main and is also a deadlock if that was not the intent.
What it costs. A select with a handful of cases is the normal way to cancel work and merge streams. A select in a tight loop without a default or a receive that eventually happens will park correctly; with default it becomes a busy poll — see select default.
Code Examples
package main
import (
"fmt"
"time"
)
func main() {
a := make(chan string, 1)
b := make(chan string, 1)
a <- "A"
b <- "B"
select {
case v := <-a:
fmt.Println(v)
case v := <-b:
fmt.Println(v)
}
}
func wait(ch <-chan int, timeout time.Duration) (int, bool) {
select {
case v := <-ch:
return v, true
case <-time.After(timeout):
return 0, false
}
}func untilCancel(ctx context.Context, ch <-chan int) {
for {
select {
case <-ctx.Done():
return
case v, ok := <-ch:
if !ok {
return
}
fmt.Println(v)
}
}
}Common Gotchas
`break` inside `select` does not exit the `for`
use a label.
`time.After` in a loop leaks timers until they fire
use `time.NewTimer` and `Stop`, or `ctx` with timeout.
Ready cases are chosen uniformly at random
do not depend on source order.
All-nil cases (and no default) block forever
All-nil cases (and no default) block forever