š» Developer by day, š® gamer by night | Software Engineer in @Taboola | ā sometimes coffee lover | A good player in call of duty | š· sometimes love photography
A channel is a communication technique which allows a Goroutine to communicate with another Goroutine.
You may notice the āmain routineā in above screenshot. As soon as the main routine run of code to execute. The entire program will quit even the other child routine is running.
Declaration
We can declare channel by writing the following syntax:
Or We can use a shorthand declaration with a builtin make() function:
Letās see some basic example:
The following output will be:
How to send data with channel?
Here 5 is the value as input which we are sending through channel with the syntax channel <- 5
We can receive the value out of channel (For e.g: when you receive text message and you read it via phone) with the syntax myNumber <- channel
To log the channel value fmt.Println(<- channel)
Letās have a quick at this simple channel program:
This program will sum up through channel:
Output:
Another simple channel example with greet message:
Output:
Letās have a quick another look at this simple channel program:
Here our channel is unbuffered (we didnāt specify any buffer size when make()ing the channel) meaning that they will only accept sends (channel <-) if there is a corresponding receive () ready to receive the sent value. So in this case āchā is an unbuffered channel and we are attempting to send onto it,
but there is no receiver of this channel.
We can fix it by either making the channel buffered or registering a receiver on this channel in another go routine.
So we might see some out error:
fatal error: all goroutines are asleep - deadlock!
To avoid this error, we can specify the buffer size:
We wonāt see error here anymore after specifying the buffer size.
Close() function
We can close the channel with builtin close() function. This sets the response with true/false value to indicate no more value will be send to the channels.
Open or close channel value can be checked with the following syntax:
Letās try with one example to check the close function:
We will see the following output:
Hope my contribution will help you to understand this topic. Please feel free to reach out to me on twitter @rajendraarora16 for any queries.