How to work with channels?

1 5 48
calendar_todayschedule1 min read
— Originally published at dev.to

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)
}

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

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

1 Comment

0 votes
🔥 Join developers growing publicly
Share your knowledge, build in public, and grow your developer presence with a global community.

More Posts

How I Built a React Portfolio in 7 Days That Landed ₹1.2L in Freelance Work

Dharanidharan - Feb 9

Your Game’s GC Spikes? Blame Yourself.

PrabashanaDev - Jul 15

Europe Just Dropped the Hammer on AI: A Wake-Up Call?

PrabashanaDev - Jul 15

I’m a Senior Dev and I’ve Forgotten How to Think Without a Prompt

Karol Modelskiverified - Mar 19

What Is SARIF and How Does It Help Security Tools Work Together?

Ganesh Kumar - Jul 4
chevron_left
1.3k Points54 Badges
60Posts
7Comments
4Connections
Right now I'm focused on LiveReview, AI code review that gives teams control over AI-generated code without slowing them down.

Related Jobs

View all jobs →

Commenters (This Week)

4 comments
2 comments
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!