go
build_error
ai_generated
true
error:无法关闭只接收 channel ch(类型为 <-chan int 的变量)
error: cannot close receive-only channel ch (variable of type <-chan int)
ID: go/close-of-receive-only-channel
80%修复率
85%置信度
0证据数
2024-09-02首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.18 | active | — | — | — |
| 1.22 | active | — | — | — |
根因分析
编译器拒绝对只接收 channel 类型调用 close()。常见于函数返回 <-chan T,但实现内部试图关闭该 channel。
English
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.
解决方案
-
97% 成功率
func producer() <-chan int { ch := make(chan int) go func() { defer close(ch) // send... }() return ch } -
93% 成功率
func producer(done <-chan struct{}) <-chan int { ch := make(chan int) go func() { defer close(ch) select { case <-done: return; default: } }() return ch }
无效尝试
常见但无效的做法:
-
90% 失败
Type conversion doesn't change directionality for close; the compiler still rejects it because the static type is receive-only.
-
70% 失败
Receivers ranging over the channel will block forever waiting for a close that never comes.