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

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-09-02First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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

  1. 97% success
    func producer() <-chan int {
        ch := make(chan int)
        go func() {
            defer close(ch)
            // send...
        }()
        return ch
    }
  2. 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:

  1. 90% fail

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

  2. 70% fail

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