Lesson 2 · Unit 08
Channels
Pass values between goroutines through pipes that keep them in step.
What you practise
- Send and receive block, buffered channels,
closeandrange,selectwith a timeout
Try a question from this lesson
Pick one
A goroutine cannot return a value to the code that started it. This one puts its result into ch, a channel, and main takes it out with <-ch. What prints?
ch := make(chan int)
go func() {
ch <- 6 * 7
}()
v := <-ch
fmt.Println(v)Hint
Taking a value out of a channel waits until there is a value to take.
Correct answer
42
Why
<-ch makes main wait until a value arrives, so it cannot run ahead and exit. The channel carries the result and does the waiting in one step: no WaitGroup, and no shared variable to guard.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Channels
A channel is a pipe between goroutines that carries values of one type. make(chan string) creates one.
ch <- v sends a value in. v := <-ch receives one. The arrow shows which way the value moves.
On a plain channel a send waits until someone receives, and a receive waits until someone sends: the value is handed over directly.
ch := make(chan string)
go func() {
ch <- "ping" // waits for a receiver
}()
msg := <-ch // waits for a sender
fmt.Println(msg) // pingConcept
Buffered channels
make(chan string, 2) gives the channel a buffer: room for two values.
A send only waits when the buffer is full, and a receive only waits when it is empty. Values come out in the order they went in.
len(ch) says how many values are waiting inside.
ch := make(chan string, 2)
ch <- "a" // does not wait: room for 2
ch <- "b"
fmt.Println(len(ch)) // 2
fmt.Println(<-ch) // a
fmt.Println(<-ch) // bConcept
select
select looks like switch, but each case is a channel operation. It waits until one of them can go ahead, and runs that case.
time.After(d) gives a channel that delivers a value after the duration d. Put it in a select and you have a timeout: wait for the answer, but not forever.
ch := make(chan string)
select {
case msg := <-ch:
fmt.Println(msg)
case <-time.After(10 * time.Millisecond):
fmt.Println("timeout") // nobody sent
}9 more exercises in the app
- 4× type the answer
- 3× multiple choice
- 1× fill the blanks
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.