Lesson 2 · Unit 03
Channels
Pipes that block: send, receive, close, range and select.
What you practise
- Unbuffered and buffered, send and receive block,
closeandrange,selectwith a timeout
Try a question from this lesson
Pick one
go cannot return a value, so this goroutine sends its result into a channel. There is no WaitGroup. What does the program print?
ch := make(chan int)
go func() {
ch <- 6 * 7
}()
v := <-ch
fmt.Println(v)Correct answer
42
Why
<-ch blocks main until a value arrives, so main 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 block
A channel is a typed pipe between goroutines: ch <- v sends, v := <-ch receives.
make(chan int) is unbuffered. A send blocks until some goroutine receives, and a receive blocks until some goroutine sends: the value is handed over directly, and both sides know it happened.
make(chan int, 3) has a buffer of three. Sends succeed without a receiver until the buffer is full; receives block only when it is empty.
ch := make(chan string)
go func() {
ch <- "ping" // waits for a receiver
}()
msg := <-ch // waits for a sender
fmt.Println(msg) // pingConcept
close and range
close(ch) says that no more values will be sent. Receivers still get everything already sent; after that a receive returns the zero value at once, and the two-result form v, ok := <-ch gives ok == false.
for v := range ch receives until the channel is closed and drained.
Only the sender closes: sending on a closed channel panics. You do not need to close every channel, only those whose receiver is waiting for the end.
ch := make(chan int)
go func() {
ch <- 1
ch <- 2
close(ch) // nothing more is coming
}()
for v := range ch {
fmt.Println(v) // 1, then 2
}Concept
select
select looks like a switch whose cases are channel operations. It blocks until one of them can proceed and runs that case. If several are ready, it picks one at random.
time.After(d) returns a channel that delivers one value after the duration d. Put it in a case and you have a timeout: the wait ends when the answer arrives or when time runs out, whichever comes first.
ch := make(chan string) // never used
select {
case msg := <-ch:
fmt.Println(msg)
case <-time.After(time.Millisecond):
fmt.Println("timeout")
}
// timeout9 more exercises in the app
- 2× multiple choice
- 1× fill the blanks
- 4× type the answer
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.