Default Selection

The default case in a select is run if no other case is ready.

Use a default case to try a send or receive without blocking:

  1. select {
  2. case i := <-c:
  3. // use i
  4. default:
  5. // receiving from c would block
  6. }

default-selection.go

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func main() {
  7. tick := time.Tick(100 * time.Millisecond)
  8. boom := time.After(500 * time.Millisecond)
  9. for {
  10. select {
  11. case <-tick:
  12. fmt.Println("tick.")
  13. case <-boom:
  14. fmt.Println("BOOM!")
  15. return
  16. default:
  17. fmt.Println(" .")
  18. time.Sleep(50 * time.Millisecond)
  19. }
  20. }
  21. }