Why does Go panic on writing to a closed channel? : <p>Why does Go panic on writing to a closed channel?</p>

<p>While one can use the <code>value, ok := &lt;-channel</code> idiom for reading from channels, and thus the ok result can be tested for hitting a closed channel:</p>

<pre><code>// reading from closed channel

package main

import "fmt"

func main() {
    ch := make(chan int, 1)
    ch &lt;- 2
    close(ch)

    read(ch)
    read(ch)
    read(ch)
}

func read(ch &lt;-chan int) {
    i,ok := &lt;- ch   
    if !ok {
        fmt.Printf("channel is closed\n")
        return
    }
    fmt.Printf("read %d from channel\n", i)
}
</code></pre>

<p>Output:</p>

<pre><code>read 2 from channel
channel is closed
channel is closed
</code></pre>

<p>Run "reading from closed channel" on <a href="http://play.golang.org/p/oJoLGeRI4S" rel="noreferrer">Playground</a></p>

<p>Writing to a possibly closed channel is more convoluted, because Go will panic if you simply try to write when the channel is closed:</p>

<pre><code>//writing to closed channel

package main

import (
    "fmt"
)

func main() {
    output := make(chan int, 1) // create channel
    write(output, 2)
    close(output) // close channel
    write(output, 3)
    write(output, 4)
}

// how to write on possibly closed channel
func write(out chan int, i int) (err error) {

    defer func() {
        // recover from panic caused by writing to a closed channel
        if r := recover(); r != nil {
            err = fmt.Errorf("%v", r)
            fmt.Printf("write: error writing %d on channel: %v\n", i, err)
            return
        }

        fmt.Printf("write: wrote %d on channel\n", i)
    }()

    out &lt;- i // write on possibly closed channel

    return err
}
</code></pre>

<p>Output:</p>

<pre><code>write: wrote 2 on channel
write: error writing 3 on channel: send on closed channel
write: error writing 4 on channel: send on closed channel
</code></pre>

<p>Run "writing to closed channel" on <a href="http://play.golang.org/p/qL7z3SVeqX" rel="noreferrer">Playground</a></p>

<p>As far as I know, there is not a simpler idiom for writing into a possibly closed channel without panicking. Why not? What is the reasoning behind such an asymmetric behavior between read and write?</p>
