panic: send on closed channel, explained

Read the explanation
What if

main reads the two values it needs and closes the channel, while the sender still has a third to send. That send panics and takes the whole program down.

0123456main: start the senderwg.Gomain: <-results: 11main: <-results: 22main: close(results)closesender: results <- 11sender: results <- 22sender: results <- 3: waitswaitssender: panic: send on closed channelpanic

Tap any block to see what that thread is doing.

  • Running
  • Waiting / parked
  • Error
Step 1/5

main starts one sender. It will send 1, 2 and 3 on an unbuffered channel.

1func main() {2    results := make(chan int)3    var wg sync.WaitGroup4    wg.Go(func() {5        for i := 1; i <= 3; i++ {6            results <- i7        }8    })9    fmt.Println(<-results)10    fmt.Println(<-results) // main only needs two11    close(results)         // done with results12    wg.Wait()13    fmt.Println("done")14}

Explanation

What just happened

main read the two values it needed and closed results. The sender was still waiting to send its third. Closing woke it up, and a send on a closed channel panics. Nothing recovered it, so the whole program stopped before done.

Try the what-if switch

Why

Closing a channel means “no more values are coming”. Only the sender knows that. When the receiver closes, any send still in flight hits a closed channel.

How to fix it

Let the goroutine that sends close the channel, once it is done, often with defer close(ch). With several senders, close after a WaitGroup says they have all finished. If the receiver wants to stop early, it should tell the senders to stop, for example with context cancellation, not close their channel.

Watch out

Closing a channel twice panics too: panic: close of closed channel.

Common questions

What causes panic: send on closed channel?

A goroutine sent on a channel that was already closed, usually because the receiver closed it while a sender still had values to send. The panic happens in the sending goroutine and stops the whole program with exit code 2.

Can recover() catch send on closed channel?

Yes. It's an ordinary panic, not a fatal error, so recover() in a deferred function of the sending goroutine catches it. That only hides the bug: let the sender close the channel instead.

Why does my message end with [recovered, repanicked]?

The goroutine was started with wg.Go, which recovers the panic and raises it again, so Go 1.26 and 1.27 add that suffix. Started with a plain go statement, it prints just panic: send on closed channel.

Does receiving from a closed channel panic too?

No. A receive on a closed channel returns the zero value and ok == false. Only sending on it, or closing it a second time (panic: close of closed channel), panics.

Verified: this timeline matches a real program, checked in CI on Go 1.26 and 1.27. How we verify. Unclear or wrong? Tell us