×

go · level 3 · unit 2 · lesson 4

  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

Arrows in a function's types say who may send and who may receive.

A parameter of type chan<- int is a : the function may send into it, but not receive. <-chan int is a : it may receive, but not send or close. A plain chan int turns into either when you pass it in.

The arrows are a promise written in the types, and the compiler holds you to it. A reader of func collect(in <-chan Order) knows at a glance that collect only takes orders out.

A common shape is the : a function that makes a channel, starts a goroutine to fill and close it, and returns it as <-chan T. Callers can only receive, so that goroutine stays the one and only sender.

package main
import "fmt"
func countTo(n int) <-chan int {
	out := make(chan int)
	go func() {
		for i := 1; i <= n; i++ {
			out <- i
		}
		close(out)
	}()
	return out
}
func main() {
	for n := range countTo(3) {
		fmt.Println("Number", n)
	}
}

main never sees the goroutine inside countTo; it only sees a channel it can read.