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
Resources
Section titled “Resources”Exercises
Section titled “Exercises”select1 test
Section titled “select1 test”select waits on multiple channel operations and proceeds with whichever
Show hint
select chooses whichever case can proceed:
select {case v := <-a: return vcase v := <-b: return v}select2 test
Section titled “select2 test”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, truecase <-time.After(d): return 0, false}select3 test
Section titled “select3 test”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, truedefault: return 0, false}