×

go · level 3 · unit 3 · lesson 2

  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

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.