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.

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.
closeof a closed or nil channel panics; so does a send on a closed channel. Receiving from a closed channel is always safe.v, ok := <-chdistinguishes a real zero value from a closed channel;range chis the idiomatic loop and ends on close.- A nil channel blocks forever on send and receive, which makes it useful as a disabled
selectcase and fatal as an uninitialized one. - With two or more senders, closing requires coordination: a
sync.WaitGroupplus a goroutine that waits and then closes, orerrgroupwith 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
selectis 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
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-onlyThe channel type's direction is part of the function signature and documents ownership:
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
| Operation | nil channel | open, unbuffered | open, buffered full | closed |
|---|---|---|---|---|
ch <- v | blocks forever | blocks until received | blocks until space | panics |
<-ch | blocks forever | blocks until sent | returns queued value | zero value, ok == false |
close(ch) | panics | closes | closes; queued values remain | panics |
len(ch) | 0 | 0 or 1 in flight | number queued | queued, then 0 |
cap(ch) | 0 | 0 | the capacity | capacity |
range ch | blocks forever | drains until close | drains until close | ends immediately |
case <-ch in select | never ready | ready when a sender waits | ready when non-empty | always 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
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 == falseclose 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
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 sendingTwo 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:
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
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
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:
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
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 symptom | Cause | Fix |
|---|---|---|
panic: send on closed channel | a sender raced with a close | close only after all senders finish (WaitGroup) |
panic: close of closed channel | two closers, or defer close plus an explicit close | one owner of the close |
panic: close of nil channel | closing an uninitialized channel | allocate it first |
fatal error: all goroutines are asleep - deadlock! | send with no receiver, or receive on nil | check the buffer and the goroutine graph |
| Loop consumes 100% CPU after a producer stops | selecting on a closed channel without ok | return on !ok, or set the channel to nil |
| Receiver sees endless zeros | treating a closed channel as data | check ok |
| Drops legitimate zero values | zero used as a sentinel | use ok or range |
| Producer goroutine never exits | receiver stopped reading | drain, buffer enough, or cancel |
invalid operation: close(ch) on a receive-only channel | receive-only channels cannot be closed | keep the send-side handle for closing |
| Values disappear from a buffered channel | capacity exceeded and a sender blocked, then process exited | size 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 toolsSmall utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Go guides
All Go guidesGo iota: Enumerations, Bitmask Flags, and Constant Expressions
How iota advances per const line, typed enums with gaps, bit flags with 1 << iota, and the unit scale pattern that shifts with one blank line.
Go JSON: Marshaling, Unmarshaling, Struct Tags, and Custom Parsers
Struct tags, omitempty that skips false and zero, custom marshalers without recursion, RawMessage for tagged unions, and float64 precision loss.
Go Strings, Runes, and Bytes: UTF-8 Encoding, Conversion, and Memory
Bytes versus runes, len that counts bytes, slicing that splits characters, Builder for linear concatenation, and normalization the standard library omits.
Go select Statement: Non-Blocking Operations, Timeouts, and Nil Channels
Random choice among ready cases, non-blocking polls with default, nil channels that disable a case, timer reuse, and labeled breaks out of a loop.
More in Go
All Go guidesThe guides filed next to this one in Go, in library order.