Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Channel is a key built-in element of Go. It is one of the elements that distinguishes Go. Channel, in conjunction with another unique feature, goroutine, makes concurrent programming more convenient, entertaining and reduces the problems of concurrent programming.
Channel is mainly used for concurrency synchronization. This post will go over all of the channel concepts, syntax, and rules. So lets discuss what exactly a channel is.
What are Channels
A channel in Go is a medium via which a goroutine communicates with another goroutine in a lock-free manner. In other terms, a channel is a mechanism that allows one goroutine to transfer data to another. The channel is bidirectional by default, which implies that goroutines can transmit and receive data over the same channel.
Creating a Channel
A channel is formed in Go using the chan keyword, and it can only transfer data of the same kind; multiple types of data cannot be sent from the same channel.
Syntax
var Channel_name chan DataType
We may also use a shortcut declaration to build a channel with the make() method.
channel_name:= make(chan Datatype)
Example
package main
import "fmt"
func main() {
// Using var keyword
var channel1 chan int
fmt.Println("Value of the channel1: ", channel1)
fmt.Printf("Type of the channel: %T ", channel1)
//using make() function
channel2 := make(chan int)
fmt.Println("\nValue of the channel2: ", channel2)
fmt.Printf("Type of the channel2: %T ", channel2)
}
Output
Value of the channel1: <nil>
Type of the channel: chan int
Value of the channel2: 0xc00006a060
Type of the channel2: chan int
Directional Channels
Channels can be directional, which means you can limit a channel to either sending or receiving data. This is shown by the arrow (<-) next to the channel declaration.
For example, in the code below,
Example
package main
import (
"fmt"
"time"
)
func main() {
n := 4
// We want to run a goroutine to multiply n by 3
go multiplyByThree(n)
// We pause the program so that the `multiplyByThree` goroutine
// can finish and print the output before the code exits
time.Sleep(time.Second)
}
func multiplyByThree(num int) int {
result := num * 3
fmt.Println(result)
return result
}
Output
12
Take a look at the type specification of the multiplyByThree function's out parameter.
out chan<- int
The chan <- declaration specifies that data can only be sent into the channel and not be received from it.
The int declaration specifies that the channel will take only int datatypes.
Although they appear to be different pieces, chan <- int may be regarded as a single data type that defines a "send-only" channel of integers.
Sending and Receiving Data Through a Channel
Channels in the Go programming language perform two primary operations: sending and receiving, which are referred to together as communication. And whether the data is received or sent is indicated by the direction of the <- operator. By default, the send and receive operations in the channel are blocked until the other side is ready. It enables goroutines to communicate with one another without the use of explicit locks or condition variables.
Blocking Statements
Statements that send or receive data from channels block within their own goroutine. That is:
A request for data from a channel will be blocked until some data is received.
A statement that sends data to a channel will wait until the data sent is received.
For example, consider the following code
Example
package main
import (
"fmt"
"time"
)
func main() {
n := 4
// We want to run a goroutine to multiply n by 3
go multiplyByThree(n)
// We pause the program so that the `multiplyByThree` goroutine
// can finish and print the output before the code exits
time.Sleep(time.Second)
}
func multiplyByThree(num int) int {
result := num * 3
fmt.Println(result)
return result
}
In this code, when attempting to print the value received (in the main function):
fmt.Println(<-out)
The <-out command will prevent the code from running until some data is received on the out channel. It is thus helpful to visualize this by dividing the main block into two parts: the portion that runs until it is time to wait for the channel to receive data and the one that runs thereafter.
The second half of the main may only be executed if data has been received over the channel.
Buffered Channels
We saw in the previous examples that channel statements block until data is transmitted into or received from a channel.
This occurs because a channel lacks a place to "store" the data that enters it and must therefore wait for a statement to receive data.
A buffered channel is a type of channel having storage capacity.
Syntax
To construct a buffered channel, we add a capacity parameter to the make method:
out := make(chan int, 3)
Out is now a buffered channel with three integer variables capacity. This implies it may take in up to three values before becoming blocked.
A buffered channel is similar to a regular channel with additional storage (or buffer)
When we don't want the channel statement to block if there are no accessible receivers, we utilize buffered channels. Adding a buffer allows us to wait for some of the receivers to become available without causing the transmitting code to be blocked.
FAQs
Why channels are used in Golang? A channel is a technique for communicating between concurrently running functions by sending and receiving data of a certain element type. When you have numerous goroutines running at the same time, channels are the most convenient method for them to interact with one another.
How do I use a channel in Golang? A channel is formed in the Go language using the chan keyword, and it can only transfer data of the same kind; multiple types of data cannot be sent from the same channel. You may also use the make() method with a shortcut declaration to construct a channel.
Are Golang channels bidirectional? All of the channels we've discussed so far are bidirectional, meaning they can send and receive data. Unidirectional channels, or channels that just send or receive data, can also be created.
Key Takeaways
In this article, we have extensively discussed the Go channel, we learned to create a channel and to send/receive data through a Go channel.
We hope that this blog has helped you enhance your knowledge on Go channel and if you would like to learn more about Go, check out our articles Golang Archives. Do upvote our blog to help other ninjas grow. Happy Coding!