Channels
This lesson will introduce you to channels - one of the most vital concepts when it comes to communication in concurrency using Go.
A channel is a pipe between goroutines to synchronize execution and communicate by sending/receiving data.
Channels are based on the idea of Communicating Sequential Processes (CSP) put forward by Hoare in 1978.
First of all, let’s just cover the basic syntax.
Creating a Channel
You can create a channel with the following syntax:
The datatype
is the type of data that you will pass on your channel. For example, to create a channel named result
of type int
, you can write:
result := make (chan int)
Sending on a Channel
You can send data over your channel by using the following syntax:
Let’s continue with our example of result
. If you want to send 2
on result
, you can do so using the following code:
result <- 2
The sending ...