go
build_error
ai_generated
true
error: cannot close receive-only channel ch (variable of type <-chan int)
ID: go/close-of-receive-only-channel
80%Fix Rate
85%Confidence
0Evidence
2024-09-02First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 1.18 | active | — | — | — |
| 1.22 | active | — | — | — |
Root Cause
The compiler rejects close() on a receive-only channel type. This surfaces when a function signature returns <-chan T but the implementation tries to close it internally.
generic中文
编译器拒绝对只接收 channel 类型调用 close()。常见于函数返回 <-chan T,但实现内部试图关闭该 channel。
Workarounds
-
97% success
func producer() <-chan int { ch := make(chan int) go func() { defer close(ch) // send... }() return ch } -
93% success
func producer(done <-chan struct{}) <-chan int { ch := make(chan int) go func() { defer close(ch) select { case <-done: return; default: } }() return ch }
Dead Ends
Common approaches that don't work:
-
90% fail
Type conversion doesn't change directionality for close; the compiler still rejects it because the static type is receive-only.
-
70% fail
Receivers ranging over the channel will block forever waiting for a close that never comes.