Reading — step 1 of 6
Learn
select waits on multiple channel operations, executing the one that's ready first. It's the foundation of timeouts, fan-in, fan-out, and cancellation in Go.
The basic shape
Each case is a channel operation (send or receive). select blocks until ANY case is ready. If multiple are ready, it picks one at random.
Timeouts
The most common select pattern: bounded waiting.
time.After(d) returns a channel that fires after duration d. If nothing arrives on ch within a second, the timeout case wins.
Default — non-blocking
Adding default makes select non-blocking:
The default runs immediately if no other case is ready. Useful for periodic polling without blocking.
Fan-in pattern
Merge multiple channels into one:
Setting a channel to nil disables its case in the select — a common idiom for managing closed channels.
Cancellation with context
In idiomatic modern Go, cancellation flows through context.Context:
Every long-running goroutine should accept a context and check ctx.Done() for cancellation.
Common mistakes
- Forgetting to close channels — receivers blocking on a closed-but-never-signaled channel leak.
- Selecting without a timeout — production code should usually have an escape hatch.
- Sending on a closed channel — panics. The sender should always own closing.
- Goroutines that never check for cancellation — leak when the caller stops needing them.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…