Golang Concepts: Nil Channels

In Go, channels are a core feature used for communication between goroutines. Channels are meant to be used for message sharing and hence when I encountered nil channels, I started to wonder why they were needed.

What are nil channels?

A nil channel in Go is a channel that has been declared but not initialized with a make statement, or explicitly set to nil.

A nil channel has the following properties:

  1. Receiving from a nil channel blocks forever.
  2. Sending to a nil channel blocks forever.
  3. Closing a nil channel panics.

Where are nil channels useful?

Let’s begin with a fundamental example involving channels, setting the stage for our exploration into the significance of nil channels:

In the above example, we create two goroutines which send messages on channels a and b. Upon completion of sending the values, they also close the channels.

In the main routine, we have an infinite loop consuming the values coming in the channels. We don’t care about the order of processing, so we use a for..select block for processing the values from the channels.

--

--

Pratik Pandey - https://pratikpandey.substack.com

Senior Engineer with experience in designing and architecting large scale distributed systems.