go · level 3 · unit 3 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
With a default case, a select never waits.
Add a default case to a select and it never waits. If no other case is ready right now, the runs at once. That gives you a send or receive: try it, and if it cannot happen, do something else.
Busy programs use this to stay quick. A logger with a full buffer drops a message instead of slowing everyone down, and counts what it dropped. A worker peeks at a channel for news without stopping its work.
Never spin round a for loop with an empty default: it keeps a processor core busy doing nothing. Use default only when there is something useful to do instead.
package main
import "fmt"
func main() {
logs := make(chan string, 2)
dropped := 0
for _, msg := range []string{"start", "load", "save", "quit"} {
select {
case logs <- msg:
default:
dropped++
}
}
fmt.Println("kept", len(logs), "dropped", dropped)
} A case can have no lines inside it: once the send succeeds there is nothing more to do.
guess first
Peek for news three times. What prints?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func main() {
news := make(chan string, 1)
check := func() string {
select {
case n := <-news:
return n
default:
return "no news"
}
}
fmt.Println(check())
news <- "the cat is home"
fmt.Println(check())
fmt.Println(check())
}
your turn
Your turn. Hand out the last few seats.
Choose how many seats there are, a number from 1 to 4. Then fill in the case that runs when every seat is taken.
output
press run to see what happens
fix it
One alert jams the whole program. Can you fix it?
output
press run to see what happens
- The buffer holds one alert. What does the second send do when it is full?
- A
selectwith no default case waits until a case is ready, and nobody ever receives. - Add a default case after the send:
default:withskipped++inside it.
nailed it
your code no longer waits when it should not. :D
- The default case runs when no other case is ready.
- A non-blocking send can drop work instead of waiting.
- Never spin a loop around an empty
default.
new words in your collection
- default case
- non-blocking
This lesson isn’t saved. A free account remembers every lesson you finish.