Fix Go "panic: close of closed channel" — A Second Close, a Nil Channel, and the Receives That Stay Safe After Close
Something closed a channel that was already closed. Maybe two goroutines both thought the close was theirs to make. Maybe a cleanup path ran after the normal shutdown path. Maybe the channel was never created at all, and the close landed on a nil channel instead. Below, each shape gets its own section: the exact output it prints, then the ownership rule that prevents it - one sender closes, exactly once, a sync.Once guard where ownership is shared, and the receive forms that stay safe on the far side of a close.
Written November 21, 2026 · Tested with Go 1.26.4 · 20 min read
- The first failure: closing the same channel twice
- The nil channel: the close lands on a channel that was never made
- Receiving from a closed channel: the drain, then zero and false
- The range loop: the receiver's half of the contract
What this guide is
You hit panic: close of closed channel when close runs on a channel that is already closed.
close(ch) does one job. It records that no more values will be sent on ch. It is a signal to receivers, not a cleanup call and not a way to free the channel. Once that signal is recorded, recording it again is meaningless — and Go treats it as a programming error, not a no-op. The second call panics on the spot.
Why doesn't the compiler stop you? Because whether a channel is closed is run-time state. The same close statement is legal the first time it runs and a panic the second time, and which run a given execution reaches depends on goroutines, branches, and error paths the compiler cannot settle. So the code builds, and the run finds out.
Closing is also asymmetric, and that asymmetry is the whole guide. Sends and closes belong to the producing side. Receives belong to the consuming side, and receives are the forgiving operation here: a receive from a closed channel can always proceed. A second close cannot. Code that treats close like free — callable from anywhere, callable twice for safety — is code written against the wrong model.
The shapes in this guide look similar in a stack trace. They aren't the same bug.
- A second close on a live channel? Two places in the code both believe they own the close.
- A close on a nil channel? The channel was never made. The bug is upstream, at the missing
make. - Receives misbehaving after a close? Usually not a close bug at all. A receiver that ignores the
okresult reads zero values forever and calls it data.
One related panic is deliberately not this guide's subject. Sending on a closed channel raises its own panic, with its own message, and it gets one short section below pointing at the guide that covers it. Here the focus stays on close itself: who may call it, how many times, and on what.
All examples use Go 1.26.4. Each one is a single main.go in one module. Make the module once, from an empty directory:
$ mkdir closechan
$ cd closechan
$ go mod init example.com/closechan
go: creating new go.mod: module example.com/closechan
After that, swap in each program as the new main.go. Transcripts come from go run -trimpath main.go. The -trimpath flag shortens file paths in the trace — you see ./main.go:9 instead of a long absolute path. Line numbers match either way. Tested with Go 1.26.4.
The first failure: closing the same channel twice
Start small. Make a channel, close it, close it again.
// main.go
package main
import "fmt"
func main() {
ch := make(chan int)
close(ch)
fmt.Println("closed once")
close(ch)
fmt.Println("after")
}
$ go run -trimpath main.go
closed once
panic: close of closed channel
goroutine 1 [running]:
main.main()
./main.go:9 +0x71
exit status 2
Read the output in order. closed once prints. The first close succeeded and did its full job: from that moment, no more values will be sent on ch, and any receiver can proceed. Then the second close panics. fmt.Println("after") never runs.
There is no partial credit and no warning. Go does not track a close count, does not return an error from close, and does not let you ask a channel whether it is closed before you close it. There is no isClosed check to hide behind. The language puts the whole burden on the program's structure: arrange the code so the close can only happen once, because nothing at run time will save a design that lets it happen twice.
In this toy the two calls sit three lines apart. In real code they never do. The production version looks like this: a worker goroutine closes its output channel when it finishes, and a supervisor's error path closes the same channel when it gives up waiting. Or a Close method on a struct runs once from a deferred call and once from an explicit shutdown. Or two consumers of a shared "done" channel each decide the work is finished. Every one of those is the same bug — two owners — wearing different clothes. When you meet this panic, don't ask which close was second. Ask why there were two closers at all.
The nil channel: the close lands on a channel that was never made
Change one thing. Declare the channel, but never make it.
// main.go
package main
import "fmt"
func main() {
var ch chan int
fmt.Println(ch == nil)
close(ch)
fmt.Println("after")
}
$ go run -trimpath main.go
true
panic: close of nil channel
goroutine 1 [running]:
main.main()
./main.go:8 +0x51
exit status 2
One word changed in the message: of nil channel instead of of closed channel. And true prints first — the comparison confirms the channel is nil at the moment of the close.
var ch chan int gives you a channel value that refers to nothing. No buffer, no queue, no state to record a close in. So the close cannot even begin: it panics immediately, in the calling goroutine, with its own distinct message. Keep that immediacy in mind, because nil channels are famous for the opposite behavior, and mixing the two up sends debugging in the wrong direction.
Here is the contrast. Sending on a nil channel blocks forever, and receiving from a nil channel blocks forever. A nil channel is never ready for communication. In a single-goroutine program that block is total, and the runtime's deadlock detector ends the program:
// main.go
package main
import "fmt"
func main() {
var ch chan int
v := <-ch
fmt.Println(v)
}
$ go run -trimpath main.go
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive (nil chan)]:
main.main()
./main.go:7 +0x25
exit status 2
Same nil channel, two completely different deaths. Block on it — send or receive — and you get the fatal deadlock error. Close it, and you get a panic, right away, naming the line that called close. So if your crash says panic: close of nil channel, do not go hunting for a deadlock. Hunt for the missing make. Somewhere upstream a channel field was never initialized, a constructor took a branch that skipped creation, or a channel arrived as a parameter that a caller left nil. The close site is where the missing initialization surfaces, not where it happened.
Receiving from a closed channel: the drain, then zero and false
Now the side of close that does not panic. Close a channel that still holds values, then keep receiving from it.
// main.go
package main
import "fmt"
func main() {
ch := make(chan int, 3)
ch <- 10
ch <- 20
ch <- 30
close(ch)
for {
v, ok := <-ch
fmt.Println(v, ok)
if !ok {
break
}
}
fmt.Println("after")
}
$ go run -trimpath main.go
10 true
20 true
30 true
0 false
after
Walk the four receives. Closing did not discard anything. The three buffered values come out first, in the order they were sent, each with ok true — true because each value was delivered by a real send. Only once the buffer is empty does the behavior change: the receive proceeds immediately, without blocking, and returns the zero value for the element type — 0 for an int channel — with ok false. That false is the signal that the channel is closed and empty. It is generated by the close, not delivered by a send, and that distinction is exactly what ok reports.
Two consequences follow, and both bite in real code.
First, a receive on a closed channel never blocks and never panics, no matter how many times you repeat it. The tenth receive after the drain returns 0 false just like the first. That makes the single-value form, v := <-ch with no ok, quietly dangerous on a channel that can close: after the drain it returns zero values forever, instantly, in a hot loop if you let it. Nothing crashes. The zeros just flow downstream dressed as data. If a channel can be closed, receive with the comma-ok form, or range over it — the next section's form — so the end of the stream is a value you branch on, not a flood you mistake for input.
Second, the drain order is a guarantee you can design around. Because values sent before the close are received before any zero value appears, a sender can close immediately after its last send without a handshake. It does not need to wait for the receiver to catch up, and no final value is lost. Close means "nothing more is coming," never "what is already here is void."
The range loop: the receiver's half of the contract
The comma-ok loop above works, but Go has a form built for exactly this shape. A for range over a channel receives until the channel is closed and empty, then ends the loop on its own.
// main.go
package main
import "fmt"
func send(ch chan<- int) {
for i := 1; i <= 3; i++ {
ch <- i * 100
}
close(ch)
}
func main() {
ch := make(chan int)
go send(ch)
for v := range ch {
fmt.Println(v)
}
fmt.Println("after")
}
$ go run -trimpath main.go
100
200
300
after
Notice who does what, because this program is the ownership rule in working form. The send function holds a send-only channel, chan<- int. It sends its three values and then, as its last act, closes the channel. The receiver in main never closes anything. It ranges, prints each value as it arrives, and the loop ends when the close lands and the channel is empty. after prints. No counts are shared, no sentinel value is agreed on, no ok is checked by hand — the close is the whole termination protocol.
Flip either half and the program breaks in one of this guide's two directions. If send never closes, the range loop blocks after 300, waiting for a fourth value that will never come; with nothing else left to run, that is the deadlock shape from the nil section, reached by omission. If main closed the channel instead — say, when it decided it had read enough — then send's next send would land on a closed channel, and a receiver closing a channel it does not own is how send-side panics are born. Receivers do not close. A receiver that wants the stream to stop stops reading, or signals the sender on a separate channel; it never closes the channel it reads from.
This is also why close is not needed at all in many programs. A channel that nobody ranges over, and where every receiver knows how many values to expect, never has to be closed. Close exists to broadcast "no more values" to receivers who cannot otherwise know the stream has ended. If that broadcast is not needed, adding a close adds an owner, a timing constraint, and a panic waiting for a second call — for nothing.
Shared ownership: the sync.Once-guarded closer
The rule "one owner closes, exactly once" is easy when one goroutine produces everything. It gets harder at shutdown boundaries. A server stops because a request failed, or because a signal arrived, or because a parent context ended — several paths, each legitimately able to trigger the close of a shared channel, none of them able to promise the others will not also fire.
The fix is not a boolean flag next to the channel. An unsynchronized check-then-close is itself a race: two goroutines can both read "not closed yet" and both call close. The fix is sync.Once. Wrap the close in a sync.Once value, and exactly one call to its Do runs the function — the first one. Every later call returns without running it.
// main.go
package main
import (
"fmt"
"sync"
)
type stream struct {
ch chan int
once sync.Once
}
func (s *stream) Close() {
s.once.Do(func() { close(s.ch) })
}
func main() {
s := &stream{ch: make(chan int, 1)}
s.ch <- 7
s.Close()
s.Close()
s.Close()
v, ok := <-s.ch
fmt.Println(v, ok)
v, ok = <-s.ch
fmt.Println(v, ok)
fmt.Println("after")
}
$ go run -trimpath main.go
7 true
0 false
after
Three Close calls, one actual close. The buffered 7 still drains first — 7 true — and the next receive reports the closed, empty channel: 0 false. after prints. Nothing panicked, and no caller had to know whether it was the first to arrive.
Two disciplines make this pattern safe rather than merely lucky. First, the sync.Once and the channel live together in the same struct, and the close call exists in exactly one place in the codebase: inside the Do. A second raw close(s.ch) written anywhere else defeats the guard completely, because the guard only serializes calls that go through it. Second, guard the close, not the sends. sync.Once makes closing idempotent; it does nothing for a goroutine that keeps sending after the close has run. If producers can outlive the trigger that closes the channel, they need their own stop signal — a done channel they select on before sending — so that by the time any Close call can fire, the sends have already wound down.
Reach for this pattern only when ownership genuinely is shared. Where a single sender produces the values, the plain sender-closes form from the range section is simpler and says more: the type signature chan<- int advertises who closes. The Once guard is for the boundary cases — shared shutdown, deferred cleanup next to explicit cleanup — where "exactly one owner" cannot be arranged, so "exactly one execution" is arranged instead.
Not this panic: sending on a closed channel
One paragraph, because the two panics are siblings and searches mix them. If a goroutine sends on a channel after the close, the message is panic: send on closed channel — a different line, a different culprit, and a different fix conversation about senders that outlive their stream. That panic has its own guide on this site, linked below. The short version that belongs here: it is almost always the mirror image of this guide's bug. Somebody closed a channel they did not own — often a receiver — or closed it before the senders had finished. Fix the ownership, and both panics go away together.
The fixed program
Here is a program that puts the pieces together without panicking. One producer runs here, written the way several producers would be: no producer closes at all. A sync.WaitGroup counts the producers, a separate goroutine waits for them all to finish and makes the single close, and the receiver ranges until that close ends the stream.
// main.go
package main
import (
"fmt"
"sync"
)
func produce(ch chan<- string, wg *sync.WaitGroup) {
defer wg.Done()
ch <- "alpha"
ch <- "beta"
}
func main() {
ch := make(chan string)
var wg sync.WaitGroup
wg.Add(1)
go produce(ch, &wg)
go func() {
wg.Wait()
close(ch)
}()
for v := range ch {
fmt.Println(v)
}
v, ok := <-ch
fmt.Printf("after close: %q %v\n", v, ok)
}
$ go run main.go
alpha
beta
after close: "" false
Check the shape against the failures above. The producer sends and returns; its deferred Done reports completion, and it never touches close — with one producer here, and the same code ready for several, no producer can race another to a second close, because no producer closes at all. The closing goroutine makes exactly one close call, and it can only run after wg.Wait() returns, which is after every producer's last send. So the close can never land early, mid-stream, either. The receiver ranges, prints alpha and beta, and the loop ends when the close arrives. The final comma-ok receive confirms the state in values: the zero value for string, "", with false.
Nothing here calls recover. Nothing asks the channel whether it is closed — there is no way to ask. The program is safe because its structure leaves exactly one close call, on exactly one path, gated on the one condition that makes it correct: all sends are done. That is the whole fix, in every program. The patterns differ — a lone sender closing its own channel, a Once at a shared boundary, a waiter goroutine collecting producers — but each one is a way of arranging that sentence.
The fixes, ranked
Give the close one owner: the sender. The goroutine that sends the values is the one that knows when there are no more. It closes, once, as its last act — ideally holding a send-only chan<- T so the code says so. Receivers never close. This comes first because it prevents the panic structurally: with one owner there is no second call to make.
When several producers feed one channel, close from a waiter, not from the producers. Count the producers with a sync.WaitGroup. A separate goroutine waits for all of them and makes the single close. No producer closes, so producers cannot race each other to a double close, and the waiter cannot close early.
Where several paths can trigger one close, guard it with sync.Once. Put the channel and the Once in the same struct, put the only close call inside the Do, and let every shutdown path call the guarded method. The first trigger wins; the rest become no-ops. This is the fix for deferred-plus-explicit cleanup and multi-cause shutdown.
Initialize every channel on every path. A close of nil channel panic means a make never ran. Construct channels where the type is constructed, not lazily at first use, and treat a nil channel arriving as a parameter as a contract question to settle at the boundary — not something the closing code should absorb.
Receive with comma-ok or range wherever a channel can close. This does not prevent the close panics, but it prevents their quiet cousin: code that reads zero values off a drained, closed channel and treats them as data. ok false, or the end of a range loop, is the end of the stream. Branch on it.
Do not answer the panic by recovering around close, or by sprinkling extra closes "for safety." A recover around a double close hides an ownership bug that will return as a send-side panic or a lost shutdown on the next path change. And a defensive second close is not defensive at all — it is the panic itself, scheduled. One close, one owner, is the safety.
Which fix for which cause
| What the message and code show | Cause | Fix |
|---|---|---|
panic: close of closed channel |
close ran twice on the same channel; two places in the code own the close |
Give the close one owner — the sender — or guard a genuinely shared close with sync.Once |
panic: close of nil channel |
The channel was never made; a make was skipped on some path |
Initialize the channel where its owner is constructed; trace back from the close site to the missing make |
| No panic; a receiver spins on zero values after the stream ends | A single-value receive on a closed, drained channel returns the zero value immediately, forever | Receive with the comma-ok form and branch on ok, or range over the channel |
| A range loop never ends after the last value | The sender never closes the channel it owns | Close from the sender after its last send; if there are several senders, close from a WaitGroup waiter |
panic: send on closed channel in the same code |
A channel was closed before its senders finished, or closed by a receiver | Restore sender ownership of the close; see the send-on-closed-channel guide below |
Checklist
- Find every
closecall for a channel that panics. More than one call site, or one call site reachable by more than one path? That is the bug. Arrange one owner, a waiter, or async.Onceguard. - Check that no receiver closes. A
closein code that also receives from the same channel is a defect, even if it has not panicked yet. - Check the nil case separately. If the message says
close of nil channel, follow the channel back to its construction and find the path wheremakenever ran. - Look for check-then-close flags. A boolean guarding a close, read and written by more than one goroutine without synchronization, is a race wearing the shape of a fix. Replace it with
sync.Once. - Audit receives on channels that can close. Single-value receives with no
okwill read zero values as data after the drain. Convert them to comma-ok or range. - Ask whether each close needs to exist. No ranging receiver and no receiver waiting on
ok? The close broadcasts to nobody. Removing it removes an owner and a possible panic.
Related guides on this site
- Fix Go "panic: send on closed channel" — Close of Closed and Nil Channels, Receiving From a Closed Channel, and select — the sibling panic. A send lands after the close instead of a second close landing after the first, and its guide works through the close-side shapes from the sender's side of the same ownership rule.
- Fix Go "fatal error: all goroutines are asleep - deadlock!" — Unbuffered Channels, Nil Channels, select, and Unclosed Ranges — the other way channel code dies. A receive or send on a nil channel blocks forever, and a range over a channel nobody closes blocks the same way; that guide covers the deadlock shapes generally, where this one stays on close semantics.
- Finding a Leaked Goroutine with Go 1.27's goroutineleak Profile — for the goroutines left behind when a stream's close never comes. A receiver parked on a channel nobody closes does not crash a busy program; it leaks, and the profile is how you find it.
Sources
- The Go Programming Language, The Go Programming Language Specification — for the close built-in (for a channel
ch,close(ch)records that no more values will be sent on the channel; it is an error ifchis a receive-only channel; sending to or closing a closed channel causes a run-time panic; closing the nil channel also causes a run-time panic; after callingclose, and after any previously sent values have been received, receive operations will return the zero value for the channel's type without blocking, and the multi-valued receive operation returns a received value along with an indication of whether the channel is closed), for the receive operator (receiving from a nil channel blocks forever; a receive operation on a closed channel can always proceed immediately, yielding the element type's zero value after any previously sent values have been received; the multi-valued formx, ok = <-chreports whether the communication succeeded —okis true if the value received was delivered by a successful send operation, false if it is a zero value generated because the channel is closed and empty), and for send statements (a send on a closed channel proceeds by causing a run-time panic; a send on a nil channel blocks forever). - The Go Programming Language, Go Concurrency Patterns: Pipelines and cancellation — for the sender-closes pattern (the
genstage starts a goroutine that sends the integers on a channel and closes the channel when all the values have been sent; thesqstage closes its outbound channel after the inbound channel is closed and it has sent all values downstream).
Keep Exploring
The full Go hub \u2014 slices and maps, concurrency, and the standard library.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.