go runtime_error ai_generated true

panic: close of nil channel

ID: go/goroutine-close-nil-channel

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2025-05-22First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.0 active
1.21 active

Root Cause

Calling close() on a nil channel, which is a programming error.

generic

中文

对nil通道调用close(),这是编程错误。

Workarounds

  1. 99% success Initialize channel before close
    ch := make(chan int)
    // use ch
    close(ch)
  2. 85% success Use sync.Once to safely close only if initialized
    var once sync.Once
    if ch != nil {
        once.Do(func() { close(ch) })
    }

Dead Ends

Common approaches that don't work:

  1. Using recover() to catch panic 90% fail

    Recover works but doesn't fix the logic; channel remains nil.

  2. Checking ch != nil before close but not initializing 80% fail

    Nil check prevents panic but channel is never initialized; subsequent operations fail.