go runtime_error ai_generated true

panic: 关闭 nil channel

panic: close of nil channel

ID: go/close-of-nil-channel

其他格式: JSON · Markdown 中文 · English
80%修复率
87%置信度
0证据数
2024-05-02首次发现

版本兼容性

版本状态引入弃用备注
1.x active — — —

根因分析

关闭了一个 nil channel,通常是因为 channel 字段未初始化,或对零值结构体调用了 close()。

English

A nil channel was closed, typically because a channel field was never initialized or a struct was created with a zero value and close() was called on it.

generic

解决方案

  1. 95% 成功率
    func NewWorker() *Worker {
        return &Worker{
            jobs: make(chan Job, 16),
            done: make(chan struct{}),
        }
    }
  2. 85% 成功率
    var once sync.Once
    func (w *Worker) Close() {
        once.Do(func() {
            if w.jobs != nil { close(w.jobs) }
        })
    }

无效尝试

常见但无效的做法:

  1. 50% 失败

    Scattered nil checks hide the real bug (missing initialization) and race with any concurrent assignment to the field.

  2. 60% 失败

    Other senders/receivers may still see nil; the channel is now created after consumers started reading.