go
runtime_error
ai_generated
true
恐慌:从已关闭的通道接收数据
panic: receive from closed channel
ID: go/goroutine-receive-from-closed-channel
80%修复率
82%置信度
0证据数
2024-02-10首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.18 | active | — | — | — |
| 1.19 | active | — | — | — |
| 1.20 | active | — | — | — |
| 1.21 | active | — | — | — |
| 1.22 | active | — | — | — |
根因分析
尝试从已关闭的通道接收数据,但仅当通道为nil时才会发生恐慌。
English
Attempting to receive from a channel that was closed while a goroutine is waiting, but the panic occurs only if the channel is nil.
解决方案
-
95% 成功率 Use comma-ok idiom to detect closed channel
v, ok := <-ch; if !ok { /* channel closed */ } -
80% 成功率 Ensure channel is not nil before receive
if ch != nil { v := <-ch }
无效尝试
常见但无效的做法:
-
Checking channel with cap() before receive
90% 失败
cap() does not indicate closed state.
-
Using recover() to ignore panic
70% 失败
Recover does not prevent data corruption.