go
runtime_error
ai_generated
true
panic: send on closed channel
ID: go/panic-runtime-error-send-on-closed-channel
85%Fix Rate
85%Confidence
1Evidence
2023-06-15First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| go1.21 | active | — | — | — |
| go1.22 | active | — | — | — |
| go1.23 | active | — | — | — |
Root Cause
Attempting to send a value on a channel that has already been closed, which violates the channel contract.
generic中文
尝试向已关闭的通道发送值,违反了通道的使用约定。
Official Documentation
https://go.dev/ref/spec#CloseWorkarounds
-
90% success Ensure the channel is closed only by the sender after all sends are complete. Use a sync.WaitGroup to coordinate goroutines, and close the channel in a dedicated goroutine after Wait.
Ensure the channel is closed only by the sender after all sends are complete. Use a sync.WaitGroup to coordinate goroutines, and close the channel in a dedicated goroutine after Wait.
-
85% success Use a select statement with a default case to check if the channel is closed before sending, or use a separate closed channel for signaling.
Use a select statement with a default case to check if the channel is closed before sending, or use a separate closed channel for signaling.
中文步骤
Ensure the channel is closed only by the sender after all sends are complete. Use a sync.WaitGroup to coordinate goroutines, and close the channel in a dedicated goroutine after Wait.
Use a select statement with a default case to check if the channel is closed before sending, or use a separate closed channel for signaling.
Dead Ends
Common approaches that don't work:
-
Adding a time.Sleep before closing the channel to avoid race conditions.
85% fail
Race conditions are timing-dependent; adding sleep does not guarantee ordering and may hide the bug rather than fix it.
-
Using recover() in a deferred function to catch the panic.
70% fail
Recovering from a panic does not fix the root cause; the channel was already misused and data may be lost.
-
Closing the channel after all sends are done by adding a sync.WaitGroup but not calling WaitGroup.Wait() correctly.
60% fail
Incorrect WaitGroup usage leads to same race: close happens before all sends complete.