// Chapter 37 example: close a channel when done, and receive with for range. // Run with: go run exercises/37/05-close-and-range.go package main import ( "fmt" "time" ) // countdown sends from..1, then closes the channel to say it is finished. func countdown(from int, out chan int) { for i := from; i >= 1; i-- { out <- i time.Sleep(200 * time.Millisecond) } close(out) } func main() { numbers := make(chan int) go countdown(5, numbers) for n := range numbers { fmt.Println(n) } fmt.Println("Liftoff!") // After close, a receive gives the zero value at once, and ok is false. n, ok := <-numbers fmt.Println(n, ok) }