Channels are tools for communication between goroutines. The chan keyword is used to define the channel:
chan element_type
After the word chan, you specify the type of data that will be transmitted using the channel. For example:
var chInt chan int
Here, the chInt variable represents a channel that passes data of type int.
To transfer data to or from a channel, the <-
operation (left-pointing arrow) is used. For example, transferring data to a channel:
chInt <- 10
In this case, the number 10 is sent to the channel. Retrieving data from a pipe to a variable:
x := <- chInt
If the number 510 was previously sent to the channel, then when performing the operation <-
chInt can receive this number in the x variable.
It is worth considering that we can send to and receive from a channel only data of the type that the channel represents. So, in the example with the chInt
channel, this is data of type int.
Typically, the sender of the data is one goroutine, and the receiver is another goroutine.
When a channel variable is simply defined, it has the value nil, which means that the channel is essentially uninitialized. The make()
function is used for initialization. Depending on the definition of channel capacity, it may be buffered or unbuffered.