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.

GoResilience

Code

gosnippet
30 lines
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

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.