Range and Close

A sender can close a channel to indicate that no more values will be sent. Receivers can test whether a channel has been closed by assigning a second parameter to the receive expression: after

  1. v, ok := <-ch

ok is false if there are no more values to receive and the channel is closed.

The loop for i := range c receives values from the channel repeatedly until it is closed.

Note: Only the sender should close a channel, never the receiver. Sending on a closed channel will cause a panic.

Another note: Channels aren't like files; you don't usually need to close them. Closing is only necessary when the receiver must be told there are no more values coming, such as to terminate a range loop.

range-and-close.go

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func fibonacci(n int, c chan int) {
  6. x, y := 0, 1
  7. for i := 0; i < n; i++ {
  8. c <- x
  9. x, y = y, x+y
  10. }
  11. close(c)
  12. }
  13. func main() {
  14. c := make(chan int, 10)
  15. go fibonacci(cap(c), c)
  16. for i := range c {
  17. fmt.Println(i)
  18. }
  19. }