Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Wednesday, April 12, 2023

Working with Channels in Golang

 n our previous tutorial, we have explained how to achieve Concurrency with Goroutines in Golang. In this tutorial we will explain about Channels in Golang and how Goroutines communicate with Channels. Channels are the pipes that used with Goroutines for sending and receiving values. We can send the values with Channels from one Goroutines and can receive those values in another Goroutines.

 

1. What is Channels in Golang

Channels in Golang is a data transfer object to pass and receive data. In technical sense, the Channels is a pipe which is used to communicate with Goroutines to transfer data from one end to other end. It’s just like a real water pipe where water flows from one end to another end, the same way data sent from one end and received other end with Channels.


2. How to declare Channels in Golang

Channels can be created with make keyword. Each channel needs data type in which data needs to transfer. There are only one data type allowed to be transferred from a channel.

values := make(chan int)

3. How to use Channels with Goroutines in Golang

Now we will create a function getValue() that computes random value and passes to channel values variable.

func getValue(values chan int) {
    value := rand.Intn(20)
    values <- value
}

In our main() function, we will create a channel values := make(chan int) and then use this channel in function getValue() Goroutines. We will pass newly created channel values in getValue() Goroutines. The function getValue() send the new value to our channel and assign to value through <-values. We finally get the new channel value through value := <-values and display the value.

func main() {
	values := make(chan int)	
	go getValue(values)
	value := <-values
	fmt.Println(value)
}

Here is the complete example file main.go about channel communication with Goroutines.

package main

import (
    "fmt"
    "math/rand"
)

func getValue(values chan int) {
    value := rand.Intn(20)
    values <- value
}

func main() {
	values := make(chan int)	
	go getValue(values)
	value := <-values
	fmt.Println("Channel value: ", value)
}

Output:


$ go run main.go
Channel value: 1

Conclusion

In this tutorial we have explained to learn about channels in Go. We have also explained how to use Channels with Goroutines in Golang. If you have any queries regarding this tutorial, then please feel free to let me know in the comments section below.

No comments:

Post a Comment