How to check if a channel is closed and send to it only if it is not closed

In Go, if the channel channel closed, I can still read from it using the following syntax, and I can check if it is closed.

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

However, if I do not know if the channel is closed and I am writing it blindly, I may get an error. I want to know if there is a way to check the channel and write to it only when it is not closed. I ask this question because sometimes I do not know if the channel is closed or not in the program.

+15
source share
3 answers

You can not. The basic rule here is that only writers should close channels, so you know that you should no longer write to this channel.

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 
+17
source

If multiple channels are writing to a channel, you can also nil it instead of close and use select to read and write. Something like that

 ch := make(chan int, 1) var value int ch <- 5 select { case value = <-ch: fmt.Println("value", value) default: fmt.Println("oops") } ch = nil select { case ch <- 5: default: fmt.Println("don't panic") } select { case value = <-ch: fmt.Println("value", value) default: fmt.Println("oops") } 

Try it working https://play.golang.org/p/sp8jk961TB

+5
source

@serejja Why are you saying

You can not

I found this gist:

https://gist.github.com/iamatypeofwalrus/84b6c7d946a6a4143a1d

please look at that. Or maybe I did not understand the question?

0
source

All Articles