Skip to content

Select

Advanced · Concurrency

select lets a goroutine wait on multiple channel operations, proceeding with whichever is ready. If several are ready it picks one at random; a default case makes it non-blocking.

  • select1 — receive from whichever channel is ready
  • select2 — timeout by racing a receive against time.After
  • select3 — non-blocking receive with default

select waits on multiple channel operations and proceeds with whichever

Show hint
select chooses whichever case can proceed:
select {
case v := <-a: return v
case v := <-b: return v
}

Source

Pairing a receive with time.After in a select implements a timeout.

Show hint
time.After(d) returns a channel that fires after d. Race it:
select {
case v := <-ch: return v, true
case <-time.After(d): return 0, false
}

Source

A default case makes a select non-blocking: it runs when no other

Show hint
A default case runs when no other case is ready, so select never blocks:
select {
case v := <-ch: return v, true
default: return 0, false
}

Source