Select

The select statement lets a goroutine wait on multiple communication operations.

A select blocks until one of its cases can run, then it executes that case. It chooses one at random if multiple are ready.

select.go

  1. package main
  2. import "fmt"
  3. func fibonacci(c, quit chan int) {
  4. x, y := 0, 1
  5. for {
  6. select {
  7. case c <- x:
  8. x, y = y, x+y
  9. case <-quit:
  10. fmt.Println("quit")
  11. return
  12. }
  13. }
  14. }
  15. func main() {
  16. c := make(chan int)
  17. quit := make(chan int)
  18. go func() {
  19. for i := 0; i < 10; i++ {
  20. fmt.Println(<-c)
  21. }
  22. quit <- 0
  23. }()
  24. fibonacci(c, quit)
  25. }