liveBook · Manning

Select statement

As explained in Go in Action, Second Edition

A select statement is a Go control construct that waits for and proceeds with a communication operation that is ready among multiple channel operations.

A Go select statement lets a goroutine wait on multiple channel operations and proceed when one is ready. It is useful in event loops that must react to work, errors, or cancellation without waiting on a single channel. section 9.4 section 9.7

Use select to coordinate concurrent work:

  • Multiplex input from different channels, such as feed requests and ingestion errors. section 9.4
  • Respond to cancellation signals or implement timeouts alongside other communication. section 9.4
  • Include a default case when the operation should not wait for a channel to become ready. section 9.4
func (a *App) run() {
 for {
  select { #1
  case feed := <-a.feedRead: #2
   ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
   go a.fetchFeed(ctx, feed)
   cancel()
  case err := <-a.errChan: #3
   fmt.Println("error:", err)
  }
 }
}

The feed-processing event loop selects between incoming feed URLs and errors. The listing cancels each fetch context immediately after starting the goroutine and does not show a shutdown path; adapt those details before use. section 9.4

A separate error channel keeps error reporting distinct from the flow of feed data. The event loop can receive and report errors while continuing to coordinate other work. section 9.4

How Go in Action, Second Edition covers it

How deep it goes
Explains readiness and default cases with an event-loop listing, but does not detail selection when multiple operations are ready.
Examples
Uses a feed-processing loop that receives feed URLs and errors on separate channels.
What you can do after
Apply select to coordinate channel-based work and error handling in an event loop.
How it connects
Connects channel communication with goroutines, cancellation, timeouts, and nonblocking operations.

Also explained in

Compare how 9 books explain select statement →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.