Module lessons (3/5)
`select`: channel multiplexing
Wait for the first ready channel, case default to not block, pattern timeout with time.After.
What you'll learn in this lesson
- Listen to multiple operations on the channel at the same time, choosing the first one ready with
select. - Implement non-blocking reads with
default:and explicit timeouts withtime.After/ctx.Done(). - Understanding the empty
select {}anti-pattern and the advanced trick of setting a channel tonilto disable its branch in the loop.
Overview
The select statement is similar to a switch statement dedicated to channel communications: it waits for at least one of its case (sending or receiving) to become ready, and if more than one are ready at the same time it chooses one at random equally.
By adding default:, the select never stops waiting if no channel is ready. In aggregation loops however, when a channel closes (ok == false), by assigning in = nil that branch will no longer be selected in subsequent iterations:
Sections covered in this lesson
- 1Basic syntax and multiplexing with timeout
- 2Non-blocking with
defaultand event loop withnilchannel - 3Disable closed branches with
nilin the fan-in - 4Reusable timeouts with
time.NewTimer - 5Guided practice
- 6Check for understanding
Unlock "`select`: channel multiplexing" and the full Course Go curriculum
Wait for the first ready channel, case `default` to not block, pattern timeout with `time.After`.
Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.
- Instant access to all advanced modules in Course Go plus 17 more courses
- Hands-on browser exercises with automated test suites and solutions
- 14-day money-back guarantee processed via Paddle.com
14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.