DEV Community

Cover image for How to work with channels?
Ganesh Kumar
Ganesh Kumar

Posted on

How to work with channels?

Hello, I'm Ganesh. I'm building git-lrc, an AI code reviewer that runs on every commit. It is free, unlimited, and source-available on Github. Star Us to help devs discover the project. Do give it a try and share your feedback for improving the product.

In this article we will understand how to work with channels.

What is a channel? Why it is needed?

Channels are used to pass data between goroutines.
They are a way to synchronize the flow of data between different parts of a program.

When to use channels?

Let's see the example below.

Have 2 goroutines to calculate the sum of an array.

First, we will calculate the sum of the first half of the array.

Second, we will calculate the sum of the second half of the array.

package main

import (
    "fmt"
)

func add(a []int, c chan int) {
    sum := 0
    for _, v := range a {
        sum += v
    }
    c <- sum
}

func main() {
    a := []int{7, 2, 8, -9, 4, 0}

    c1 := make(chan int)
    go add(a[:len(a)/2], c1)

    c2 := make(chan int)
    go add(a[len(a)/2:], c2)

    x, y := <-c1, <-c2
    fmt.Println(x, y, x+y)
}
Enter fullscreen mode Exit fullscreen mode

Finally, we will print the sum of the first half and the second half of the array.

Output:

gk@jarvis:~/exp/code/rd/go-exmaple$ go run main.go 
17 -5 12
Enter fullscreen mode Exit fullscreen mode

Conclusion

Channels play a crucial role in concurrent programming by enabling safe communication and synchronization between goroutines.
This makes it easier to build concurrent programs that are both efficient and safe.
git-lrc

Any feedback or contributors are welcome! It’s online, source-available, and ready for anyone to use.
⭐ Star it on GitHub: https://github.com/HexmosTech/git-lrc

Top comments (0)