Skip to content
Codewilds

Lesson 34 of 38 · Concurrency

Go Buffered Channels, close and range

medium20 XP4 min read

Unbuffered channels hand over one value at a time, with both goroutines meeting at the channel. Two more tools turn channels into real data streams: a buffer, which lets a sender run ahead of the receiver, and close, which tells receivers that no more values are coming.

Buffered channels

make(chan T, n) creates a channel with room for n values. A send only blocks when the buffer is full, and a receive only blocks when it is empty:

package main

import "fmt"

func main() {
	ch := make(chan string, 2)
	ch <- "sword"
	ch <- "shield" // no receiver needed yet: the buffer has room
	fmt.Println(len(ch), cap(ch))
	fmt.Println(<-ch, <-ch)
}
2 2
sword shield

len(ch) is the number of values waiting in the buffer and cap(ch) is its size. A third send to this full channel would block until someone receives. Buffers smooth out bursts between a fast producer and a slower consumer, but they don't cure deadlocks: a program that only works with a buffer of exactly the right size is usually wrong.

Closing a channel

close(ch) announces that no more values will be sent. Receivers can still drain the values already in the buffer; after that, every receive returns immediately with the zero value. The comma-ok form tells the two cases apart:

ch := make(chan int, 2)
ch <- 7
close(ch)

v, ok := <-ch
fmt.Println(v, ok)
v, ok = <-ch
fmt.Println(v, ok)
7 true
0 false

ok is false only when the channel is closed and empty. Closing is a message from the sender to the receivers, so only the sender closes: sending on a closed channel panics with send on closed channel, and closing a channel twice panics too. Not every channel needs closing — close one when its receivers need to know that the stream has ended.

range over a channel

for v := range ch receives values until the channel is closed and empty. It is the receive loop you will write most often:

for v := range ch {
	fmt.Println(v)
}

If the sender forgets to close, the loop keeps waiting after the last value, and the program dies with fatal error: all goroutines are asleep - deadlock!.

Generators and pipelines

A generator is a function that returns a receive-only channel and fills it from its own goroutine:

func countdown(from int) <-chan int {
	out := make(chan int)
	go func() {
		defer close(out)
		for i := from; i > 0; i-- {
			out <- i
		}
	}()
	return out
}

func main() {
	for n := range countdown(3) {
		fmt.Println(n)
	}
	fmt.Println("liftoff!")
}
3
2
1
liftoff!

countdown returns immediately; the values are produced while the caller consumes them, and defer close(out) closes the channel when the goroutine is done.

Connect functions that take a <-chan T and return a new <-chan T, and you get a pipeline: every stage runs in its own goroutine, receives from the previous stage, transforms the values and sends them on. Stages are small, independent and easy to recombine — double(countdown(3)) or double(onlyOdd(countdown(3))).

Common mistakes

  • Forgetting to close: a range over the channel never ends, which leads to a deadlock.
  • Closing on the receiving side: the sender may still send and panic. The goroutine that sends is the one that closes.
  • Sending before returning the channel: a generator that sends in its own body, instead of in a goroutine, blocks forever on an unbuffered channel. Start the goroutine and return the channel immediately.
  • Expecting a buffer to fix a deadlock: it only delays it until the buffer is full.

Assignment

Build a small pipeline from four functions:

  1. Generate(n int) <-chan int returns a channel that delivers 1, 2, …, n and is then closed. For n <= 0 the channel is closed right away.
  2. Collect(ch <-chan int) []int receives every value until ch is closed and returns them in order.
  3. Squares(in <-chan int) <-chan int is a pipeline stage: it sends the square of every value it receives from in and closes its output once in is closed.
  4. Evens(in <-chan int) <-chan int is a filter stage: it forwards only the even values (negative ones and zero included) and closes its output once in is closed.

The starter closes each output channel immediately so that it never hangs — replace those placeholder lines with your goroutines.

Collect(Generate(4))                 // [1 2 3 4]
Collect(Squares(Generate(4)))        // [1 4 9 16]
Collect(Squares(Evens(Generate(6)))) // [4 16 36]

Premium lesson

Unlock the full Learn Go course

  • All 38 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 9 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Keep learning

Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.

Lesson last updated on .

Write code ↓
Go+20 XP

Lesson 34 is part of the full course. The first 9 lessons are free.

Premium lesson

Unlock the full Learn Go course

  • All 38 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 9 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.