How to test if a channel is close and only send to it when it's not closed

Just a learner picture Just a learner · Aug 29, 2016 · Viewed 32.6k times · Source

In Go, if a channel channel is closed, I can still read from it using the following syntax and I can test ok to see if it's closed.

value, ok := <- channel
if !ok {
    // channel was closed and drained
}

However, if I don't know whether a channel is closed and blindly write to it, I may got an error. I want to know if there is any way that I can test the channel and only write to it when it's not closed. I ask this question is because sometimes I don't know if a channel is closed or not in a goroutine.

Answer

serejja picture serejja · Aug 29, 2016

You can't. The rule of thumb here is that only writers should close channels, this way you know that you shouldn't write to that channel anymore.

Some simple code would look like this:

for i := 0; i < 100; i++ {
    value := calculateSomeValue()
    channel <- value
}

close(channel) //indicate that we will no more send values