A channel in Golang can be understood by visualizing it as a tunnel that is used to communicate between two points. Data is sent from one end of the channel and is received on the other end. Values are sent or received using the channel operator <-
, and the data flows in the direction of the arrow.
By default, channels in Golang are unbuffered, which results in them being blocking in nature. This means that subsequent values of data can only be sent after previously sent values have been received.
The blocking nature of channels can be inefficient when you want to send data values without having to wait for the other end to respond. Golang provides buffered channels, which allow you to specify a fixed length of buffer capacity so one can send that number of data values at once. These channels are only blocked when the buffer is full.
Likewise, the channel on the receiving end will only block when the buffer is empty.
Let’s look at how to declare a buffered channel:
In a buffered channel, the capacity of the buffer is specified while declaring the variable.
package mainfunc main(){//buffered channel declaration// ch:= make(chan type, capacity)ch2:= make (chan int, 10)}
Now, let’s see an example of sending and receiving data from a buffered channel:
package mainimport "fmt"func main() {ch := make(chan int, 3)ch <- 5ch <- 10ch <- 15fmt.Println(<-ch)fmt.Println(<-ch)fmt.Println(<-ch)}