liveBook · Manning

Close function

As explained in Learn Concurrent Programming with Go

close is a Go built-in function that marks a channel as closed so that no further values can be sent to it.

In a channel-based pipeline, a sender eventually needs to tell receivers that no more values will arrive. Go’s built-in close(channel) function marks a channel closed. After closing it, sending another value raises an error, so the sender must close only after its final send. section 7.1.4

Receivers can continue consuming values that were sent before the close. A receive from an exhausted closed channel returns the data type’s default value, such as 0 for int; that value alone cannot reliably distinguish closure because it may be valid application data. section 7.1.4

Stop when the channel closes

A receiver can use the two-value receive form: msg, more := <-messages. The more flag is true while the channel remains open and false after it is closed and drained. The receiver can then return instead of repeatedly processing default values. A simpler equivalent is for msg := range messages, which consumes values until closure. A sender can send 1, 2, and 3, then call close(msgChannel); the receiver prints those values and finishes.

Closing also provides a completion signal for staged work. A pipeline stage can collect words while reading its input, detect that the input channel has closed, sort the accumulated results, and send the ten longest words on its output channel. Deferring close(longWords) ensures downstream consumers can detect completion. section 9.2.4

How Learn Concurrent Programming with Go covers it

How deep it goes
Explains closure, post-closure reads, the open flag, range loops, and pipeline flushing, but not channel implementation internals.
Examples
Uses integer messages, comma-ok receives, range loops, and a longest-words pipeline that flushes results on closure.
What it assumes
Assumes basic channels, sends, receives, and goroutines while introducing sentinel values and closure-based completion.
What you can do after
Apply it by closing channels after final sends and stopping receivers with the open flag or a range loop.
How it connects
Connects channel closure with sentinel values, goroutines, pipelines, buffered channels, and message passing.

Also explained in

Compare how 3 books explain close function →

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.