With a single channel, a plain send or receive is enough. Real concurrent programs rarely have just one: a goroutine might wait for data from several sources, or need to give up if nothing arrives before a deadline. Go's select statement covers this case. It lets a goroutine wait on several channel operations at once and react to whichever one becomes ready first.

The select statement

At a glance, select looks like switch. Both use case clauses, both execute the matching branch, and both compile down to a decision tree. The syntax is similar too:

Go
select {case msg := <-ch1:    fmt.Println("received from ch1:", msg)case ch2 <- 42:    fmt.Println("sent to ch2")}

Each case must be a channel operation, either a send (ch <- value) or a receive (value := <-ch, <-ch). Unlike switch, you cannot put arbitrary boolean expressions in select cases.

Switch vs select

The resemblance to switch ends at the syntax. The two constructs behave very differently:

switchselect
Cases areEvaluated top-to-bottomEvaluated simultaneously
Branches onFirst true conditionFirst ready channel
BlocksNever (unless channel op in case)Until at least one case is ready
DefaultOptional short-circuitOptional non-blocking escape

The main difference is simultaneous evaluation. In a switch, Go checks each case in order and stops at the first match. In a select, Go checks all cases at the same time and picks among the ones that are ready.

Go
ch1 := make(chan string, 1)ch2 := make(chan string, 1)ch1 <- "one"ch2 <- "two"select {case msg := <-ch1:    fmt.Println(msg)case msg := <-ch2:    fmt.Println(msg)}

Both channels already have a value, so both cases are ready immediately. A switch would always pick ch1 because it's listed first. A select makes no such guarantee.

Simultaneous evaluation and pseudo-random selection

When multiple cases are ready at the same time, Go picks one using pseudo-random uniform selection: every ready case has an equal probability of being chosen. The Go designers chose this on purpose. If select always favored the first ready case, programs that relied on it would pass their tests and then starve lower-priority channels under load, and picking at random keeps any one case from being favored.

Go
package mainimport "fmt"func main() {    ch1 := make(chan string, 1)    ch2 := make(chan string, 1)    ch1 <- "from ch1"    ch2 <- "from ch2"    for i := 0; i < 5; i++ {        select {        case msg := <-ch1:            fmt.Println(msg)            ch1 <- "from ch1"        case msg := <-ch2:            fmt.Println(msg)            ch2 <- "from ch2"        }    }}

Run this a few times and you'll get different orderings, with neither channel winning every time.

The default case

If no channel is ready and the select has a default clause, Go executes it immediately instead of blocking. This turns select into a non-blocking operation:

Go
select {case msg := <-ch:    fmt.Println("received:", msg)default:    fmt.Println("no message available")}

This is useful for polling: checking whether data is available without committing to wait for it. Be careful, though, because a select with a default inside a tight loop becomes a busy-wait that burns CPU. Use it only when you really want to proceed without data, and keep using real synchronization for everything else.

Timeouts with time.After

Blocking forever is usually a bug, since a goroutine waiting on a channel that never sends will leak. time.After returns a channel that receives a value after the specified duration, which makes it a natural fit for select timeouts:

Go
import "time"select {case msg := <-ch:    fmt.Println("received:", msg)case <-time.After(2 * time.Second):    fmt.Println("timed out")}

If ch delivers a message within two seconds, the first case runs. If two seconds pass with nothing, time.After's channel fires and the second case runs, so the goroutine never blocks indefinitely.

The for-select pattern

A single select decides once and exits. Most goroutines need to keep reacting, whether that's reading from a stream, processing work items or watching for a shutdown signal. The idiomatic way to do this is for-select: an ordinary for loop whose body is a select.

Go
func worker(jobs <-chan int, done <-chan struct{}) {    for {        select {        case j, ok := <-jobs:            if !ok {                fmt.Println("jobs channel closed")                return            }            fmt.Println("processing job", j)        case <-done:            fmt.Println("shutting down")            return        }    }}

The goroutine runs the loop and blocks at select on each iteration until either a job arrives or the done channel signals shutdown. You'll see this pattern throughout the Go standard library, and most long-lived goroutines are built on it.

A few things to notice in the example:

  • The ok idiom (j, ok := <-jobs) detects a closed channel. When a channel is closed and drained, ok is false. Checking it prevents the goroutine from looping forever on zero values.
  • The done channel uses struct{}. An empty struct has zero size and is the conventional type for signal-only channels that carry no data.
  • Both return statements are explicit. A break inside a select only breaks out of the select, not the enclosing for. To exit the loop from within a select, use return, or break with a labeled outer loop.

Putting it together

Here is a small self-contained example that combines for-select, a timeout, and a done signal to show how the pieces interact:

Go
package mainimport (    "fmt"    "time")func generate(done <-chan struct{}) <-chan int {    out := make(chan int)    go func() {        defer close(out)        for i := 0; ; i++ {            select {            case out <- i:            case <-done:                return            }        }    }()    return out}func main() {    done := make(chan struct{})    nums := generate(done)    timeout := time.After(100 * time.Millisecond)    for {        select {        case n := <-nums:            fmt.Println(n)        case <-timeout:            fmt.Println("timeout reached, stopping")            close(done)            return        }    }}

generate sends incrementing integers until done is closed. main reads them in a for-select loop, and after 100 milliseconds the timeout case fires, closes done, and returns. The generator goroutine sees the closed done channel in its own for-select and exits cleanly.

select, usually inside a for loop, is how you build goroutines that respond to events and can be cancelled. Every goroutine you launch should have a way to exit, and the done channel shown here is one of the most common ways to give it one. Without one, goroutines that block indefinitely leak. The memory they hold keeps adding up and nothing reports it, so a leak is easy to introduce and hard to notice.