go runtime_error ai_generated true

panic: 关闭 nil channel

panic: close of nil channel

ID: go/close-of-nil-channel

其他格式: JSON · Markdown 中文 · English
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.

generic

解决方案

  1. 95% 成功率
    type Worker struct {
        jobs chan Job
    }
    func NewWorker() *Worker {
        return &Worker{jobs: make(chan Job, 16)}
    }
  2. 90% 成功率
    var once sync.Once
    once.Do(func() { close(w.jobs) })

无效尝试

常见但无效的做法:

  1. 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.

  2. 85% 失败

    Hides the defect and leaks the goroutines that are waiting on the never-created channel.