Skip to main content
Module 7 · Lesson 3 of 533/50 in the course~12 min
Module lessons (3/5)

`select`: channel multiplexing

Lesson preview5 hands-on exercises readyCourse Go · Module 7 — Competition

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 with time.After / ctx.Done().
  • Understanding the empty select {} anti-pattern and the advanced trick of setting a channel to nil to 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

  1. 1Basic syntax and multiplexing with timeout
  2. 2Non-blocking with default and event loop with nil channel
  3. 3Disable closed branches with nil in the fan-in
  4. 4Reusable timeouts with time.NewTimer
  5. 5Guided practice
  6. 6Check for understanding
Pro Lesson · Module 7 — Competition

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.