Go core
Browse topics

select statements

Version
1.27
Review
Draft

Summary#

A select waits until one of several channel sends or receives can proceed. If none is ready and there is a default clause, it runs immediately. A case on a nil channel is never ready.

Syntax#

go
select {
case value, ok := <-input:
case output <- result:
default:
}

Example#

go
package main

import "fmt"

func main() {
	odds := make(chan int, 2)
	evens := make(chan int, 2)

	select {
	case value := <-odds:
		fmt.Println("received", value)
	default:
		fmt.Println("nothing ready")
	}

	odds <- 1
	odds <- 3
	evens <- 2
	evens <- 4
	close(odds)
	close(evens)

	total := 0
	for odds != nil || evens != nil {
		select {
		case value, ok := <-odds:
			if !ok {
				odds = nil // disable this case
				continue
			}
			total += value
		case value, ok := <-evens:
			if !ok {
				evens = nil
				continue
			}
			total += value
		}
	}
	fmt.Println("total", total)
}

Expected output#

Text
nothing ready
total 10

Common mistakes#

When several communications are ready, Go picks one with equal probability, so listing a case first gives it no priority. Once a closed channel is drained, its receive case stays ready with ok == false. Set the channel variable to nil or exit the loop to stop selecting that case. A plain break leaves the select. Use a labeled break or return to leave the surrounding loop.

Version applicability#

The syntax and example work from Go 1.0.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0