go
runtime_error
ai_generated
true
恐慌:运行时错误:从 nil 通道接收
panic: runtime error: receive from nil channel
ID: go/channel-receive-from-nil
80%修复率
84%置信度
0证据数
2024-07-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.20 | active | — | — | — |
| 1.21 | active | — | — | — |
根因分析
尝试从 nil 通道接收,导致永久阻塞,但如果 select 中有 default 可能不会恐慌;然而直接接收会恐慌。
English
Attempting to receive from a channel that is nil, causing permanent block, but if in select with default, it may not panic; however, direct receive panics.
解决方案
-
100% 成功率 Initialize channel before use
ch := make(chan int); go func() { ch <- 1 }(); val := <-ch -
90% 成功率 Use select with default to handle nil channel gracefully
select { case val := <-ch: use(val); default: // skip }
无效尝试
常见但无效的做法:
-
Checking ch == nil before receive and returning
30% 失败
Check prevents panic but may cause silent data loss.
-
Using recover to catch panic
50% 失败
Panic is recoverable but indicates logic error; data not received.