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
90%Confidence
0Evidence
2024-03-04First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0+ active

Root Cause

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

中文

对未用 make() 初始化、或经条件赋值后变为 nil 的 channel 变量调用了 close()。

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 70% fail

    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% fail

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