Nil Channels Always Block
In this post, we will discuss a useful idiom in Go that makes use of the fact
that receiving and sending on nil
channels will always block:
// Create an uninitialized (nil) channel.
var ch chan struct{}
// Receiving on a nil channel blocks forever.
<-ch
// Sending on a nil channel will also block forever.
ch <- struct{}{}
This might not seem very useful at first, and may have even
introduced bugs in your programs in the past (for example,
if you forget to initialize your channels with make
before
you use them). However, this property can be leveraged in
a couple of clever ways, especially when you need to dynamically
disable a case in a select
statement: