Channels
A channel is a pipe or mailbox between helpers.
One helper sends a value. Another helper receives it.
Channels are typed. A chan string only carries strings.
Go's idea is: do not share memory by fighting over it. Share by sending messages.
Creating a channel
Create with make(chan T).
That builds an empty pipe ready for values of type T.
Send and receive
Send with ch <- value.
Receive with v := <-ch.
Unbuffered channels wait until both sides are ready. Like handing a note face to face.
Buffered channels
make(chan T, n) creates a mailbox with room for n items.
Sends can succeed without a receiver until that mailbox is full.
Think of a tray that holds a few letters before someone picks them up.
Closing a channel
The sender should close the channel when no more values will be sent.
Only the sender closes. Never close from the receiver side.
Range until closed
Receivers can range until the channel is closed.
The loop stops when the pipe has no more mail.
Only the sender closes a channel. Never close from the receiver side.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.