go
runtime_error
ai_generated
true
panic: close of nil channel
ID: go/panic-close-of-nil-channel
80%Fix Rate
88%Confidence
0Evidence
2024-05-10First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 1.18 | active | — | — | — |
| 1.22 | active | — | — | — |
Root Cause
close() is called on a channel variable that was never initialized with make(), so it holds the nil zero value.
generic中文
对一个从未用 make() 初始化的 channel 变量调用 close(),其值为 nil 零值。
Workarounds
-
95% success
Initialize the channel at declaration: ch := make(chan int). Never use var ch chan int without assignment if it will be closed.
-
93% success
Use a struct constructor that always makes the channel, e.g. func NewWorker() *Worker { return &Worker{jobs: make(chan Job)} }.
Dead Ends
Common approaches that don't work:
-
75% fail
Skipping the close leaves the channel open forever, so receivers block indefinitely; the underlying logic bug remains.
-
85% fail
Creating a fresh channel at close time means no other goroutine holds a reference to it; the close is meaningless.