go
runtime_error
ai_generated
true
错误:在 nil 通道上的 select 永久阻塞
error: select on nil channel blocks forever
ID: go/nil-channel-blocks-forever
80%修复率
88%置信度
0证据数
2024-09-12首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.0 | active | — | — | — |
| 1.21 | active | — | — | — |
| 1.22 | active | — | — | — |
根因分析
向 nil 通道发送或从 nil 通道接收会永久阻塞。在 select 中,nil 通道分支永远不会就绪,若所有分支都是 nil,select 会无限阻塞。
English
Sending to or receiving from a nil channel blocks forever. In a select, a nil channel case is never ready, so if all cases are nil, the select blocks indefinitely.
解决方案
-
95% 成功率
var ch chan int = make(chan int) select { case v := <-ch: _ = v case <-time.After(time.Second): } -
85% 成功率
var never chan struct{} // nil disables the case select { case <-never: case <-ch: }
无效尝试
常见但无效的做法:
-
85% 失败
With default, the select always takes the default branch, so nothing ever happens; the intended wait is lost.
-
75% 失败
The outer select still holds the nil reference; the goroutine's new channel is unrelated.