×

go · level 3 · unit 2 · lesson 3

  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

close says no more values are coming, and range stops there.

A receiver often does not know how many values will arrive. The sender tells it with close(ch): a promise that nothing more is coming. Values already sent can still be received. A loop for v := range ch takes every value, then stops by itself once the is empty.

Receiving from a closed, empty channel never waits: it hands back the zero value at once. To tell the difference, write v, ok := <-ch. ok is false when the channel is closed and empty.

Only the sender closes, and only once. Sending on a closed channel panics, and so does closing it twice. A receiver never closes, because it cannot know whether another value was on its way.

package main
import "fmt"
func countdown(from int, out chan int) {
	for n := from; n > 0; n-- {
		out <- n
	}
	close(out)
}
func main() {
	nums := make(chan int)
	go countdown(3, nums)
	for n := range nums {
		fmt.Println(n)
	}
	fmt.Println("Lift off!")
}

n-- takes one away, the opposite of n++.