go
runtime_error
ai_generated
true
panic: close of nil channel
ID: go/goroutine-close-nil-channel
80%Fix Rate
86%Confidence
0Evidence
2025-05-22First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 1.0 | active | — | — | — |
| 1.21 | active | — | — | — |
Root Cause
Calling close() on a nil channel, which is a programming error.
generic中文
对nil通道调用close(),这是编程错误。
Workarounds
-
99% success Initialize channel before close
ch := make(chan int) // use ch close(ch)
-
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:
-
Using recover() to catch panic
90% fail
Recover works but doesn't fix the logic; channel remains nil.
-
Checking ch != nil before close but not initializing
80% fail
Nil check prevents panic but channel is never initialized; subsequent operations fail.