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
- sender closes: the sender closes
resultsafter its last send, and main reads withrange. All three values arrive and the program ends normally.
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