go · level 3 · unit 3 · lesson 1
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Go picks at random each round. What are the totals?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func main() {
red := make(chan int, 3)
blue := make(chan int, 3)
red <- 1
blue <- 1
red <- 1
redVotes, blueVotes := 0, 0
for i := 0; i < 3; i++ {
select {
case <-red:
redVotes++
case <-blue:
blueVotes++
}
}
fmt.Println("red", redVotes, "blue", blueVotes)
}
your turn
Your turn. Send something to the help desk.
Choose which channel gets a message, orders or complaints, and type the message. The select handles whichever one you picked.
output
press run to see what happens
fix it
The total prints, then the program hangs. Can you fix it?
output
press run to see what happens
- The total appears, then Go reports a deadlock. Which loop is still going round?
- Inside a
select,breakonly leaves theselect, not theforloop around it. - Change
breaktoreturn, somainends once the total is printed.
nailed it
your goroutines can listen to many channels. :D
selectruns whichever case is ready first.- Several ready cases? Go picks one at random.
breakinside aselectleaves only theselect.
new words in your collection
- select
- ready
This lesson isn’t saved. A free account remembers every lesson you finish.