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 feed ingester may need to accept new feed URLs while also reporting failures from feeds already being processed. Waiting on either channel alone would leave the other kind of event unattended. A select statement lets one goroutine wait for multiple channel operations and proceed with one that is 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 application loop receives a URL from feedRead or an error from errChan. The feed case starts a fetch; the error case reports the failure. The timeout context is created inside the feed case, not as another select case. section 9.4

Keep data and error reporting on separate channels so a failed fetch can report its error while other work continues. Other select cases can respond to cancellation; a default case permits a nonblocking operation. Handle errors explicitly and close channels when they are no longer needed. section 9.4 section 9.7

How Go in Action, Second Edition covers it

How deep it goes
Shows a two-channel receive loop and describes cancellation, timeout, and default-case uses without implementing those select cases.
Examples
Uses a feed-ingestion loop that receives feed URLs or errors on separate channels.
What it assumes
Builds on goroutines and channels, including sending errors between concurrent tasks.
What you can do after
Build it from scratch: write a Go event loop that responds to whichever of two channel operations is ready.
How it connects
Connects channels and goroutines with error handling, cancellation, and event loops.

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.