select waits on multiple channel operations—like a switch for communication. First ready case wins; if none ready, blocks unless default provides non-blocking behavior.
Patterns
select {
case v := <-ch:
fmt.Println(v)
case <-time.After(time.Second):
fmt.Println("timeout")
default:
fmt.Println("no channel ready")
}
Use select for timeouts, fan-in, and cancellation signals—common in Kubernetes controllers and network servers.
Important interview questions and answers
- Q: select with default?
A: Non-blocking—runs default if no other case ready immediately. - Q: Multiple cases ready?
A: Go chooses pseudo-randomly among ready cases—do not assume priority without design.
Self-check
- What does select do?
- When use default in select?
Cancellation pattern
Combine select with context.Context done channel to abort long operations. In servers, one goroutine per request often selects on client disconnect and work completion.
Empty select{} blocks forever—sometimes used to park main in tiny demos, never in production servers.
Tip: Combine select with context.Done() for timeouts—standard in Kubernetes operators and HTTP handlers.
Interview prep
- select with default?
Non-blocking when no case ready—useful for polling or avoiding deadlock.
- Multiple ready cases?
Go chooses pseudo-randomly among ready cases.