Bitpath

Lesson 2 · Unit 03

Channels

Pipes that block: send, receive, close, range and select.

13 exercisesabout 3 min

What you practise

  • Unbuffered and buffered, send and receive block, close and range, select with 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?

Go
ch := make(chan int)
go func() {
  ch <- 6 * 7
}()
v := <-ch
fmt.Println(v)

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.

Go
ch := make(chan string)
go func() {
  ch <- "ping" // waits for a receiver
}()
msg := <-ch // waits for a sender
fmt.Println(msg) // ping

Concept

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.

Go
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.

Go
ch := make(chan string) // never used
select {
case msg := <-ch:
  fmt.Println(msg)
case <-time.After(time.Millisecond):
  fmt.Println("timeout")
}
// timeout

9 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.

One email when Bitpath is ready to try. Nothing else. Privacy