MiddleCodeCommonNot answered yet
Receive from, send to, and re-close a closed channel — predict each
For each of the three numbered lines, state exactly what happens at runtime (a returned value, a block, or a panic with its message) and explain why.
ch := make(chan int, 1)
close(ch)
v, ok := <-ch // (1)
ch <- 1 // (2)
close(ch) // (3)
Predict the outcome of each line.
Receiving from a closed channel returns the zero value with ok == false, so (1) gives v == 0, ok == false. Sending on a closed channel panics with send on closed channel, so (2) panics. Closing an already-closed channel also panics, so (3) panics. Rule: the sender closes, never the receiver, and only once.
- ✗Thinking a receive from a closed channel blocks instead of returning the zero value with
ok == false - ✗Believing a closed channel still accepts sends — it panics
- ✗Assuming
closeis idempotent — re-closing panics
- →How do you safely coordinate closing when there are multiple senders?
- →Why does ranging over a closed channel terminate cleanly while a bare receive returns zeros forever?
Contents
Predict each line
ch := make(chan int, 1)
close(ch)
v, ok := <-ch // (1)
ch <- 1 // (2)
close(ch) // (3)
Result
(1) v == 0, ok == false // receive from a closed channel
(2) panic: send on closed channel
(3) panic: close of closed channel // if we reached here
Closed-channel rules
- (1) Receiving from a closed channel does not block: it yields any buffered values, then the type's zero value with
ok == false. Here the buffer is empty, so immediately0, false. This is exactly howrangeknows to stop. - (2) Sending on a closed channel always panics:
send on closed channel. A close signals "no more values," so new sends are forbidden. - (3) Re-closing also panics:
close of closed channel. (The program would already have crashed on line 2 — but line 3 on its own panics.)
⚠️ Rule: the sender closes, exactly once. The receiver never closes; with multiple senders, coordinate the close through a single owner goroutine or sync.Once.
Contents