Channels in Go

Send values between goroutines with channels, close and range over them, and wait on several at once with select.

Channels are how goroutines pass values to each other and wait for each other. This section covers how sends and receives block, how to finish a stream of values with close, and how to wait on several channels at once.

Unbuffered and Buffered Channels

make(chan T) creates an unbuffered channel, where a send waits for a receiver. make(chan T, n) holds up to n values before senders wait.

ch := make(chan int)
go func() { ch <- 42 }()
fmt.Println(<-ch)

Closing and Ranging Over Channels

for v := range ch stops only when the sender calls close(ch). Only senders close, and closing twice or sending after close panics.

A missing close means a stuck loop:

If nobody closes the channel, a range loop waits forever and you get all goroutines are asleep - deadlock! or a leaked goroutine.

The select Statement

select waits on several channels, with time.After for timeouts, default for non-blocking tries, and a done channel to stop loops.

Summary

Know who is on the other side of every send and receive, close from the sender side, and give every waiting select a way out.

Unbuffered and Buffered Channels in Go

How Go channels send and receive values between goroutines, the difference between unbuffered and buffered channels, and when a send blocks.

Closing and Ranging Over Channels in Go

Why a range loop over a channel never stops until the channel is closed, who should call close, and the panics caused by closing wrongly.

The select Statement in Go

How select waits on several channels at once, how to add timeouts with time.After, non-blocking sends and receives with default, and stopping loops cleanly.