Channels
We've seen how to create concurrent code via Goroutines, how to synchronize it with WaitGroup, how to perform atomic operations, and how to temporarily stop the concurrency in order to synchronize access to shared variables. We will now introduce a different concept, the channel, which is typical of Go. A channel is what the name essentially suggests – it's something where messages can be piped, and any routine can send or receive messages through a channel. Similar to a slice, a channel is created the following way:
var ch chan int ch = make(chan int)
Of course, it is possible to instantiate the channel directly with the following:
ch := make(chan int)
Just like with slices, we can also do the following:
ch := make(chan int, 10)
Here, a channel is created with a buffer of 10 items.
A channel can be of any type, such as integer
, Boolean
, float
, and any struct
that can be defined, and even slices and pointers, though the last two are generally...