liveBook · Manning

Nil channel

As explained in Learn Concurrent Programming with Go

A nil channel is a Go channel value with no associated channel resource on which communication operations block indefinitely.

A nil channel is a Go channel value with no associated channel resource. Sending to it or receiving from it blocks indefinitely, so later statements may never execute. If every goroutine becomes blocked, Go reports a deadlock. section 8.1.6

The useful pattern is disabling select cases. A send or receive involving a nil channel remains blocked, so select ignores that case while considering other ready cases. After an input channel closes, assigning nil to its variable prevents the closed-channel case from executing repeatedly. section 8.1.6

Combining sales and expenses

Two generator goroutines produce sales and expense amounts on separate channels. The receiving loop selects between them, adds sales, subtracts expenses, and sets a channel to nil when it reports no more data. The loop continues until both channel variables are nil, then prints the end-of-day profit or loss.

How Learn Concurrent Programming with Go covers it

How deep it goes
Explains blocking, deadlock detection, closed-channel behavior, and a complete two-channel coordination pattern.
Examples
Uses a blocked string send, deadlock output, and an accounting aggregator consuming sales and expense streams.
What it assumes
Assumes channels, channel operations, select statements, goroutines, and channel closure.
What you can do after
Apply it via Go select statements to disable channel cases after their input streams close.
How it connects
Connects nil channels with Go channels, select statements, goroutines, closed channels, and message passing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Concurrent Programming with Go. The section links point to the parts of the book it draws on.