go · level 3 · unit 2 · lesson 4
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
shout may only receive. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func shout(words <-chan string) {
for w := range words {
fmt.Println(w + "!")
}
close(words)
}
func main() {
words := make(chan string, 2)
words <- "hip"
words <- "hooray"
close(words)
shout(words)
}
your turn
Your turn. Write a ticket generator.
Fill in the return type so callers can only receive from the channel, then choose the first ticket number.
output
press run to see what happens
fix it
The arrows point the wrong way. Can you fix it?
output
press run to see what happens
- Read the error.
doubletries to receive fromin, but its type says it may only send there. doubletakes values out ofinand puts values intoout. The arrows should say the same.- Change the first line to
func double(in <-chan int, out chan<- int) {.
nailed it
your channels now say who does what. :D
chan<- Tmay only send;<-chan Tmay only receive.- A generator returns
<-chan Tand closes it itself. - The compiler stops sends and closes on the wrong end.
new words in your collection
- send-only channel
- receive-only channel
- generator
This lesson isn’t saved. A free account remembers every lesson you finish.