×

go · level 3 · unit 3 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

waits on several channels and takes the first that is .

Sometimes a goroutine has more than one channel to listen to. A select holds a list of cases, and each case is a send or a receive. It waits until one of them can go ahead, then runs that case, and only that case.

A case is ready when its channel operation could happen right now: a value is waiting to be received, or there is room to send. If several are ready at once, Go picks one at random, so your program must never depend on which.

A case can receive without keeping the value, as in case <-done:. Put a select inside a for loop to keep listening, and leave the loop when the work is over.

package main
import "fmt"
func main() {
	pizza := make(chan string)
	curry := make(chan string)
	go func() { curry <- "curry for table 4" }()
	select {
	case p := <-pizza:
		fmt.Println("Serving", p)
	case c := <-curry:
		fmt.Println("Serving", c)
	}
}

Nobody ever sends pizza, so the curry case is the only one that can become ready.