Go Gopher How to Go

Go's select statement lets a goroutine wait on multiple communication operations. A select blocks until one of its cases can run, then it executes that case. It chooses one at random if multiple are ready.

💡 Key Points

  • select lets a goroutine wait on multiple channel operations.
  • select blocks until one of its cases can run.
  • If multiple cases are ready, select chooses one at random.
  • A default case can be used to prevent select from blocking.
  • select is often used to implement timeouts and cancellations.

Using Select

Here is an example of using select to wait on two channels.

package main

import (
	"fmt"
	"time"
)

func main() {
	c1 := make(chan string)
	c2 := make(chan string)

	go func() {
		time.Sleep(1 * time.Second)
		c1 <- "one"
	}()
	go func() {
		time.Sleep(2 * time.Second)
		c2 <- "two"
	}()

	for i := 0; i < 2; i++ {
		select {
		case msg1 := <-c1:
			fmt.Println("received", msg1)
		case msg2 := <-c2:
			fmt.Println("received", msg2)
		}
	}
}
Output:
received one
received two

Select Statement Patterns

PatternExampleUse Case
Multiple channelsselect { case &lt;-ch1: case &lt;-ch2: }Wait on multiple operations
Default caseselect { case &lt;-ch: default: }Non-blocking receive
Timeoutcase &lt;-time.After(1 * time.Second):Time-bounded operation
Done channelcase &lt;-done:Cancellation signal
Send on channelcase ch &lt;- value:Non-blocking send (with default)