Bitpath

Lesson 2 · Unit 08

Channels

Pass values between goroutines through pipes that keep them in step.

13 exercisesabout 3 min

What you practise

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

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

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.

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

Concept

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.

Go
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)    // b

Concept

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.

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

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