go
runtime_error
ai_generated
true
panic: 关闭 nil channel
panic: close of nil channel
ID: go/close-of-nil-channel
80%修复率
90%置信度
0证据数
2024-03-04首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.0+ | active | — | — | — |
根因分析
对未用 make() 初始化、或经条件赋值后变为 nil 的 channel 变量调用了 close()。
English
close() was called on a channel variable that was never initialized with make() or was set to nil, typically after a failed conditional assignment.
解决方案
-
95% 成功率
type Worker struct { jobs chan Job } func NewWorker() *Worker { return &Worker{jobs: make(chan Job, 16)} } -
90% 成功率
var once sync.Once once.Do(func() { close(w.jobs) })
无效尝试
常见但无效的做法:
-
70% 失败
This masks the real bug: the channel was supposed to be created. Downstream senders/receivers now block forever on a nil channel instead of panicking, turning a crash into a hang.
-
85% 失败
Hides the defect and leaks the goroutines that are waiting on the never-created channel.