State and signaling
Exploring the semantics of state and signaling puts you ahead of the curve in avoiding more straightforward bugs or making good design choices.
State
Although Go eased the adoption of concurrency with channels, there are some characteristics and pitfalls.
We should remember that channels have three states – nil, open (empty, not empty), and closed. These states strongly relate to what we can and cannot do with channels, whether from the sender’s or receiver’s perspective.
Consider a channel when you want to read from:
- Reading to a
write-only
channel results in a compilation error - If the channel is
nil
, reading from it indefinitely blocks your goroutine until it is initialized - Reading will be blocked in an
open
andempty
channel until data is available - In an
open
andnot empty
channel, reading will return data - If the channel is
closed
, reading it will return the default value for its type andfalse
to indicate...