Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Go Channels: Closing Channels, Range over Channels, and Idiomatic Patterns

Closing as a sender's statement, buffered values delivered after close, coordinating multiple senders, and the closed channel that spins a select loop.

~5 min readGo
#Go#Concurrency#Channels
3D illustration of a channel queue draining data packets through a range loop until closed safely

Closing a channel is a statement about senders: no more values will be sent. Receivers observe it as a receive that succeeds immediately with the zero value and ok == false, and a range over the channel ends. Everything that goes wrong with channels in production — double closes, sends on a closed channel, goroutines blocked forever on a nil channel, a select spinning at full CPU because a closed channel is always ready — comes from treating close as a receiver-side operation or from closing from a place that does not own all the senders.

Quick Summary

  • Only a sender closes, and only when it is the last or only sender; a receiver never closes a channel it reads.
  • Closing signals completion; it does not clear buffered values, which are still delivered before the zero-value stream begins.
  • close of a closed or nil channel panics; so does a send on a closed channel. Receiving from a closed channel is always safe.
  • v, ok := <-ch distinguishes a real zero value from a closed channel; range ch is the idiomatic loop and ends on close.
  • A nil channel blocks forever on send and receive, which makes it useful as a disabled select case and fatal as an uninitialized one.
  • With two or more senders, closing requires coordination: a sync.WaitGroup plus a goroutine that waits and then closes, or errgroup with the same shape.
  • len(ch) is the queued count, not the number of pending sends, and reading it is never a substitute for synchronization.
  • A closed channel's case in a select is always ready, so a loop that keeps selecting on it burns CPU unless the case is removed by setting the channel to nil.

Basic syntax and type signatures

go
ch := make(chan int) // unbuffered buf := make(chan int, 8) // buffered, capacity 8 go func() { defer close(ch) for i := 0; i < 3; i++ { ch <- i } }() for v := range ch { // ends when ch is closed fmt.Println(v) } v, ok := <-buf // ok == false means closed and drained _ = v; _ = ok var onlySend chan<- int = ch // send-only var onlyRecv <-chan int = ch // receive-only

The channel type's direction is part of the function signature and documents ownership:

go
func produce(out chan<- int) { defer close(out); out <- 1 } // producer closes func consume(in <-chan int) { for v := range in { _ = v } } // consumer never closes func fanIn(sources ...<-chan int) <-chan int { out := make(chan int) var wg sync.WaitGroup for _, src := range sources { wg.Add(1) go func(src <-chan int) { defer wg.Done() for v := range src { out <- v } }(src) } go func() { wg.Wait() close(out) // the only goroutine allowed to close `out` }() return out }

Channel states and operations

Operationnil channelopen, unbufferedopen, buffered fullclosed
ch <- vblocks foreverblocks until receivedblocks until spacepanics
<-chblocks foreverblocks until sentreturns queued valuezero value, ok == false
close(ch)panicsclosescloses; queued values remainpanics
len(ch)00 or 1 in flightnumber queuedqueued, then 0
cap(ch)00the capacitycapacity
range chblocks foreverdrains until closedrains until closeends immediately
case <-ch in selectnever readyready when a sender waitsready when non-emptyalways ready

The "always ready" row is the one that causes silent bugs, because a closed channel looks like a channel with data to a select that does not check ok.

Practical edge cases and deep dives

1. Closing with buffered values still queued

go
ch := make(chan int, 3) ch <- 1 ch <- 2 close(ch) for v := range ch { fmt.Println(v) // 1, then 2 } fmt.Println(<-ch, len(ch)) // 0 0 — zero value, ok == false

close marks the channel; it does not discard what is in the buffer. Receivers drain the queued values first, then see the closed state. This is why a buffered channel can be closed by the producer without losing work: everything sent before the close is still delivered exactly once. The subtlety is that a len(ch) taken after the close still reports the queued items, and a len(ch) == 0 check is not a completion signal — a producer between sends also leaves it at zero.

2. Multiple senders need a coordinating closer

go
func merge(chans ...<-chan string) <-chan string { out := make(chan string) var wg sync.WaitGroup for _, c := range chans { wg.Add(1) go func(c <-chan string) { defer wg.Done() for s := range c { out <- s } }(c) } go func() { wg.Wait() // all senders finished close(out) // exactly one close, after the last send }() return out } // The wrong version, which panics sooner or later: go func() { close(out) }() // may close while another goroutine is sending

Two senders and no coordination produce panic: send on closed channel on whichever goroutine loses the race. Two closers produce panic: close of closed channel. The WaitGroup pattern puts both decisions in one goroutine that cannot run before wg.Wait() returns, which is why it appears in nearly every fan-in. When a single function sends and closes, defer close(ch) is enough and is the clearest form:

go
func generate(n int) <-chan int { ch := make(chan int) go func() { defer close(ch) for i := 0; i < n; i++ { ch <- i } }() return ch }

3. Comma-ok, sentinel zero values, and the closed check

go
func consume(ch <-chan int) (sum int) { for { v, ok := <-ch if !ok { return sum // channel closed and drained } sum += v } } // A zero value is a legitimate payload, so it cannot mean "closed". ch := make(chan int, 2) ch <- 0 ch <- 0 close(ch) for v := range ch { fmt.Println("value", v) // prints twice; range does not stop at zero }

Code that stops on if v == 0 { return } silently drops real zeros and, worse, leaves the channel undrained if the producer is still sending. The two correct forms are for v := range ch when only the completion signal matters, and the explicit v, ok loop when the receiver must react to the close before returning. The third form, _, ok := <-ch in a select with other cases, is a mistake unless ok is checked — otherwise a closed channel keeps winning the select and delivers zeros forever.

4. The closed channel in select that never stops

go
func worker(done <-chan struct{}, jobs <-chan int) { for { select { case <-done: return case j, ok := <-jobs: if !ok { return // needed: without it, this case is always ready } process(j) } } } // Busy-loop version: no ok check, no nil assignment. func broken(done <-chan struct{}, jobs <-chan int) { for { select { case <-done: return case j := <-jobs: // after close, j is always 0 and this spins process(j) } } }

Once jobs is closed, its case is always ready, so the loop spins consuming CPU and calling process(0) as fast as the scheduler allows. The fix is either to return on !ok or to remove the case by setting the channel variable to nil — jobs = nil makes that case never ready, which is the documented use of a nil channel:

go
func drain(jobs <-chan int, done <-chan struct{}) { for jobs != nil { select { case <-done: return case j, ok := <-jobs: if !ok { jobs = nil continue } process(j) } } }

5. Abandoning a channel leaks the sender

go
func search(ctx context.Context, ch chan<- string) { for _, s := range []string{"a", "b", "c"} { select { case ch <- s: case <-ctx.Done(): return } } } func caller() { ch := make(chan string) // unbuffered go search(context.Background(), ch) fmt.Println(<-ch) // takes one value and returns // the producer is now blocked forever on ch <- "b": the goroutine leaks } func callerFixed() { ch := make(chan string, 8) // buffered: the producer can finish ctx, cancel := context.WithCancel(context.Background()) defer cancel() go search(ctx, ch) fmt.Println(<-ch) cancel() // tells the producer to stop }

A goroutine blocked on a send that will never be received stays alive with its stack, and any value it holds stays reachable. The two defenses are a buffer large enough for everything the producer might send, or a cancellation signal the producer selects on. buffered + ctx covers both. The same reasoning applies to a range over a channel that is abandoned mid-iteration: the sender blocks on the next send, so a producer that is expensive to stop should be given a done channel rather than relying on the receiver to drain.

Common mistakes and compiler errors

Error or symptomCauseFix
panic: send on closed channela sender raced with a closeclose only after all senders finish (WaitGroup)
panic: close of closed channeltwo closers, or defer close plus an explicit closeone owner of the close
panic: close of nil channelclosing an uninitialized channelallocate it first
fatal error: all goroutines are asleep - deadlock!send with no receiver, or receive on nilcheck the buffer and the goroutine graph
Loop consumes 100% CPU after a producer stopsselecting on a closed channel without okreturn on !ok, or set the channel to nil
Receiver sees endless zerostreating a closed channel as datacheck ok
Drops legitimate zero valueszero used as a sentineluse ok or range
Producer goroutine never exitsreceiver stopped readingdrain, buffer enough, or cancel
invalid operation: close(ch) on a receive-only channelreceive-only channels cannot be closedkeep the send-side handle for closing
Values disappear from a buffered channelcapacity exceeded and a sender blocked, then process exitedsize the buffer or add flow control

The discipline that removes nearly all of these is ownership: one goroutine, or one clearly defined closer, sends and closes; every receiver treats the channel as read-only; and anything that can stop early either drains to completion or signals through a cancellation channel. A channel that is closed by its receiver, or closed twice defensively, is a design that will panic under load — the panic is just the first time the race went the wrong way.

Try matching browser tools

All tools

Small utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Go guides

More in Go

All Go guides

The guides filed next to this one in Go, in library order.