What is a channel?

A channel is a communication mechanism that, among other things, allows goroutines to exchange data. Firstly, each channel allows the exchange of a particular data type, which is also called the element type of the channel, and secondly, for a channel to operate properly, we need someone to receive what is sent via the channel. We should declare a new channel using make() and the chan keyword (make(chan int)), and we can close a channel using the close() function. We can declare the size of a channel by writing something like make(chan int, 1).

What is a pipeline?

A pipeline is a virtual method for connecting goroutines and channels so that the output of one goroutine becomes the input of another goroutine, using channels to transfer our data. One of the benefits that we get from using pipelines is that there is a constant data flow in our program, as no goroutine or channel has to wait for everything to be completed in order to start their execution. Additionally, we use fewer variables and, therefore, less memory space because we do not have to save everything as a variable. Finally, the use of pipelines simplifies the design of the program and improves its maintainability.

Writing to and reading from a channel

Writing the value val to channel ch is as easy as writing ch <- val. The arrow shows the direction of the value, and we will have no problem with this statement as long as both var and ch are of the same data type.

We can read a single value from a channel named c by executing <-c. In this case, the direction is from the channel to the outer world. We can save that value into a variable using aVar := <-c.

Coding example

Both channel reading and writing are illustrated in channels.go, which comes with the following code:

Get hands-on with 1200+ tech skills courses.