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

其他格式: JSON · Markdown 中文 · English
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.

generic

解决方案

  1. 97% 成功率
    func producer() <-chan int {
        ch := make(chan int)
        go func() {
            defer close(ch)
            // send...
        }()
        return ch
    }
  2. 93% 成功率
    func producer(done <-chan struct{}) <-chan int {
        ch := make(chan int)
        go func() {
            defer close(ch)
            select { case <-done: return; default: }
        }()
        return ch
    }

无效尝试

常见但无效的做法:

  1. 90% 失败

    Type conversion doesn't change directionality for close; the compiler still rejects it because the static type is receive-only.

  2. 70% 失败

    Receivers ranging over the channel will block forever waiting for a close that never comes.