Send On Closed Channel Panics
Receiving from a closed channel stays safe and drains buffered values before zero-and-false, while a send panics until recover catches it.
Code
package main
import "fmt"
func main() {
jobs := make(chan int, 2)
// buffered values can still be received after close
jobs <- 1
close(jobs)
v, ok := <-jobs
fmt.Println("buffered value survives close:", v, ok)
// empty closed channel: zero value and false immediately
v, ok = <-jobs
fmt.Println("empty closed channel:", v, ok)
// send on a closed channel panics; recover contains it
func() {
defer func() {
if r := recover(); r != nil {
fmt.Println("recovered:", r)
}
}()
jobs <- 2
}()
fmt.Println("main continues after recover")
}What the demo separates
A buffered channel of capacity 2 holds one value, then close(jobs) runs. Receiving stays safe: the first read returns the buffered 1 with ok true, and the second read, now that the channel is drained, returns the zero value with ok false.
Sending is the unsafe side. The send is wrapped in a function whose deferred recover catches the runtime panic send on closed channel; the recovered text is printed and main continues, which is why the final line runs at all.
Points worth noting
- close drains in order: buffered values first, then zero-and-false.
- recover catches the panic text, but the send itself still did not happen.
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What exactly does the recovered panic say?
- The runtime panic value is the string send on closed channel; the demo prints it after recover, and main continues running afterwards.
Report a problem with this exampleOpens a pre-filled issue on GitHub.