go · level 3 · unit 2 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A is a pipe that carries values between goroutines.
A channel carries values of one type between goroutines. Make one with make(chan string). Send a value into it with ch <- "ready", and receive one with msg := <-ch. The arrow always points the way the value travels.
A channel made like this is : it has no room to store anything. A send waits until another goroutine receives, and a receive waits until someone sends. They meet, hand over and both carry on. Go programmers call this waiting , which has nothing to do with a block of code.
Because a receive waits, a channel can stand in for a WaitGroup when you need one answer back: main receives, and cannot go on until the goroutine has sent.
package main
import "fmt"
func brew(order string, ready chan string) {
ready <- order + " is ready"
}
func main() {
ready := make(chan string)
go brew("flat white", ready)
fmt.Println(<-ready)
} <-ready is a value like any other, so you can print it, store it or add it up.
guess first
Three scores are sent, two are received. What prints?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func main() {
scores := make(chan int)
go func() {
scores <- 10
scores <- 20
scores <- 5
}()
first := <-scores
second := <-scores
fmt.Println(first, second)
}
your turn
Your turn. Weigh the fruit in a goroutine.
Fill in the type the channel carries, pick a fruit, and receive the weight from the channel inside the Println.
output
press run to see what happens
fix it
This parcel is stuck at the depot. Can you fix it?
output
press run to see what happens
- Read the error: all goroutines are asleep.
mainis stuck on line 5. - An unbuffered send waits for a receiver, and the only receiver is
mainitself, one line further down. - Send from a goroutine instead:
go func() { results <- "parcel delivered" }().
nailed it
values now travel between goroutines. :D
ch <- vsends and<-chreceives.- An unbuffered channel makes sender and receiver meet.
- A receive waits, so it can wait for a result.
new words in your collection
- channel
- unbuffered
- blocking
This lesson isn’t saved. A free account remembers every lesson you finish.