go runtime_error ai_generated true

panic: close of nil channel

ID: go/close-of-nil-channel

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-05-02First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.x active — — —

Root Cause

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

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 50% fail

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

  2. 60% fail

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