Go Select
The select statement lets a goroutine wait on several channel operations at once. It looks like a switch, but every case is a send or a receive. select blocks until one of the cases can proceed, then runs that case. If several are ready at the same time, it picks one at random.
select {
case msg := <-inbox:
// a message arrived
case result <- value:
// our value was sent
case <-time.After(time.Second):
// nothing happened for one second
default:
// nothing was ready right now (makes select non-blocking)
}Waiting on two channels
package main
import "fmt"
func main() {
numbers := make(chan int)
words := make(chan string)
done := make(chan struct{})
go func() {
numbers <- 1
words <- "two"
numbers <- 3
close(done)
}()
for {
select {
case n := <-numbers:
fmt.Println("number:", n)
case w := <-words:
fmt.Println("word:", w)
case <-done:
fmt.Println("done")
return
}
}
}number: 1
word: two
number: 3
done
The sender goroutine sends one value at a time on unbuffered channels, so only one case is ever ready — the output order is fixed.
Non-blocking operations with default
A default case runs immediately when no other case is ready. This turns a blocking send or receive into a "try" operation.
package main
import "fmt"
func trySend(ch chan string, msg string) {
select {
case ch <- msg:
fmt.Println("queued:", msg)
default:
fmt.Println("queue full, dropped:", msg)
}
}
func main() {
queue := make(chan string, 2)
trySend(queue, "a")
trySend(queue, "b")
trySend(queue, "c")
select {
case m := <-queue:
fmt.Println("took:", m)
default:
fmt.Println("nothing to take")
}
}queued: a
queued: b
queue full, dropped: c
took: a
Timeouts
time.After(d) returns a channel that receives a value after duration d. Combined with select, it puts a time limit on waiting. Here the "slow" job deliberately takes longer than the limit, so the outcome is predictable:
package main
import (
"fmt"
"time"
)
func fetch(delay time.Duration) <-chan string {
ch := make(chan string, 1) // buffered: the goroutine can finish even if nobody listens
go func() {
time.Sleep(delay)
ch <- fmt.Sprint("data after ", delay)
}()
return ch
}
func main() {
select {
case res := <-fetch(10 * time.Millisecond):
fmt.Println("got", res)
case <-time.After(1 * time.Second):
fmt.Println("timed out")
}
select {
case res := <-fetch(2 * time.Second):
fmt.Println("got", res)
case <-time.After(50 * time.Millisecond):
fmt.Println("timed out")
}
}got data after 10ms
timed out
Note the buffer of 1 in fetch: when we time out, nobody receives from ch. Without the buffer, the goroutine would block forever on its send — a goroutine leak.
Nil channels disable a case
A receive from a nil channel blocks forever, so a select case on a nil channel is never chosen. Setting a channel variable to nil is a neat trick to switch off a case once that channel is closed — for example, when merging two streams:
package main
import "fmt"
func emit(values ...string) <-chan string {
ch := make(chan string)
go func() {
for _, v := range values {
ch <- v
}
close(ch)
}()
return ch
}
func main() {
a := emit("a1", "a2", "a3")
b := emit("b1", "b2")
countA, countB := 0, 0
for a != nil || b != nil {
select {
case _, ok := <-a:
if !ok {
a = nil // a is finished: disable this case
continue
}
countA++
case _, ok := <-b:
if !ok {
b = nil
continue
}
countB++
}
}
fmt.Println("from a:", countA, "from b:", countB)
}from a: 3 from b: 2
The interleaving of a and b values is random, which is why the example counts them instead of printing each one.
select feature |
Behaviour |
|---|---|
No case ready, no default |
blocks |
No case ready, has default |
runs default immediately |
| Several cases ready | one is chosen at random |
| Case on a nil channel | never selected |
select {} |
blocks forever |
Tip: In real programs the timeout case is usually
<-ctx.Done()from acontext.Context— that is covered in the Context chapter.
Test yourself
What does select do if two cases are ready at the same time?
- Runs both
- Runs the first one written
- Chooses one at random
- Panics
What is the effect of a default case in select?
- It runs after every other case
- It makes the select non-blocking
- It handles closed channels
- It is required
Why set a channel variable to nil inside a select loop?
- To close it
- To free memory
- To disable its case, since nil channels are never ready
- To restart it