Channels
Channels are typed conduits for sending and receiving values between goroutines — "Don't communicate by sharing memory; share memory by communicating." Unbuffered channels synch…
Introduction
Channels are typed conduits for sending and receiving values between goroutines — "Don't communicate by sharing memory; share memory by communicating." Unbuffered channels synchronize sender and receiver; buffered channels decouple them up to capacity.
Closing a channel signals no more values — receivers get zero value and ok=false. Sending on closed channel panics. Channels are the primary coordination primitive in Go alongside sync primitives.
Master channel direction (<-chan, chan<-), range-over-channel, and select for building robust concurrent pipelines.
The story
Uber's dispatch pipeline sends ride requests through channels to matching workers — producers enqueue, consumers dequeue, and backpressure naturally forms when matchers fall behind surge demand. Unbuffered channels synchronize handoff: the sender blocks until a worker receives, preventing unbounded memory growth during Black Friday traffic spikes.
Channels are typed conduits: chan Order carries order structs, not arbitrary interface{} values, keeping concurrent code type-safe.
Understanding the topic
Key concepts
- ch := make(chan int) unbuffered — send blocks until receive.
- ch := make(chan int, 10) buffered — send blocks when full.
- ch <- val send; val := <-ch receive.
- close(ch) signals done; receive returns (zero, false) when drained.
- Directional types: send-only chan<- int, receive-only <-chan int.
- range ch receives until channel closed.
Step-by-step explanation
- Unbuffered: send and receive must meet — rendezvous synchronization.
- Buffered: send succeeds until buffer full, then blocks.
- Only sender should close — receiving side detects close via ok.
- Select multiplexes multiple channel operations.
- Nil channel blocks forever — used to disable select cases.
- Channel of struct{} for signal-only (no data payload).
Practical code example
Pipeline with unbuffered channel and graceful close:
package mainimport "fmt"func producer(out chan<- int) {for i := 1; i <= 5; i++ {out <- i}close(out)}func consumer(in <-chan int) {for val := range in {fmt.Printf("received %d\n", val)}fmt.Println("channel closed, consumer done")}func main() {ch := make(chan int)go producer(ch)consumer(ch)}
Output
received 1 received 2 received 3 received 4 received 5 channel closed, consumer done
Line-by-line code explanation
func producer(out chan<- int) {takes a send-only channel. Inside this function the channel can be sent to and closed, but not received from.out <- isends the numbers 1 to 5 in a loop. The channel is unbuffered, so each send waits until the consumer is ready to receive.close(out)tells the receiver that no more values will arrive. The sending side is the one that should close a channel.func consumer(in <-chan int) {takes a receive-only channel, which documents that this function only reads from it.for val := range in {receives values one by one until the channel is closed and empty. Each value is printed withfmt.Printf("received %d\n", val), giving received 1 through received 5.fmt.Println("channel closed, consumer done")runs only after the range loop ends, which happens because the producer closed the channel.ch := make(chan int)creates an unbuffered channel of ints, so the sender and receiver have to meet at each hand-off.go producer(ch)runs the producer in its own goroutine. Thenconsumer(ch)runs on main's goroutine, and when it returns the program ends. The two-way channel ch converts automatically to the one-way types the functions expect.
Key takeaway: Only producer closes. range loops until close. Directional channel types document intent in function signatures.
Real-world use
Where you'll use this in production
- Worker job distribution in parallel processors.
- Result aggregation from multiple API calls.
- Done signaling for graceful shutdown.
- Rate limiting with ticker channel and token bucket.
Best practices
- Only the sender closes the channel.
- Use buffered channels when producer/consumer speeds differ.
- Document ownership — who sends, who receives, who closes.
- Prefer context cancellation over arbitrary channel timeouts.
- Use directional channel types in function signatures.
Common mistakes
- Closing channel on receiver side — send panic.
- Sending on closed channel — panic.
- Forgetting close — range loops forever.
- Unbuffered channel causing deadlock with single goroutine.
- Sharing channel without clear ownership model.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionBuffered vs unbuffered channel?+
Answer
2BeginnerQuestionWho closes a channel?+
Answer
3IntermediateQuestionReceive from closed channel?+
Answer
4IntermediateQuestionNil channel behavior?+
Answer
5AdvancedQuestionImplement fan-in merging multiple channels.+
Answer
Summary
Channels coordinate goroutines with typed send/receive. Unbuffered syncs; buffered decouples with capacity limit. Only sender closes; receivers detect via range or ok flag. Use directional types and clear ownership conventions. Next lesson: buffered channels — tuning backpressure.