go · level 3 · unit 2 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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++.
guess first
Two receives from a channel holding one snack. What prints?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func main() {
snacks := make(chan string, 2)
snacks <- "crisps"
close(snacks)
a, ok1 := <-snacks
b, ok2 := <-snacks
fmt.Printf("%q %v %q %v\n", a, ok1, b, ok2)
}
your turn
Your turn. Fill the basket, then empty it.
Close the channel when the producer is done, choose three items, and fill in the keyword that loops over a channel.
output
press run to see what happens
fix it
The total never arrives. Can you fix it?
output
press run to see what happens
- All four squares arrive, then
mainwaits forever. What is therangeloop waiting for? rangeover a channel only stops once the channel is closed, and nobody closes this one.- Add
close(out)after the loop insquares.
nailed it
your loops know when to stop. :D
close(ch)promises that no more values are coming.rangeover a channel stops once it is closed and empty.- Only the sender closes, and never sends after closing.
new words in your collection
- closed channel
This lesson isn’t saved. A free account remembers every lesson you finish.