tags:

views:

53

answers:

2

How do I check if a channel has a value for me to read?

I don't want to block when reading a channel. I want to see if it has a value. If it does have one, I'll read it. If it doesn't have one (yet), I'll do something else and check back again later.

Thanks!

+6  A: 

From the docs:

If a receive expression is used in an assignment or initialization of the form

x, ok = <-ch
x, ok := <-ch
var x, ok = <-ch

the receive operation becomes non-blocking. If the operation can proceed, the boolean variable ok will be set to true and the value stored in x; otherwise ok is set to false and x is set to the zero value for its type

nos
+1  A: 

If you're doing this often then it's probably not a great design and you might be better off spawning another goroutine to do whatever work you're planning to do when there isn't anything to read from the channel. The synchronous/blocking nature of Go's channels make code easier to read and reason about while the scheduler and cheap goroutines means that async calls are unnecessary since waiting goroutines take up very little resources.

Jessta