How to work with channels?

●1 ●28 ●98
calendar_today • schedule1 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

Want more #data & #between deep dives?

Join 6,091+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

1 Comment

0 votes

More Posts

Your Game’s GC Spikes? Blame Yourself.

PrabashanaDev - Jul 15

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

PrabashanaDev - Jul 15

Attention-Free Score: How Domain Reports Show Which Pages Need Work

ApogeeWatcherverified - Sep 1

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

Dharanidharan - Feb 9

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

Ganesh Kumar - Jul 4
chevron_left
1.5k Points • 127 Badges
68Posts
6Comments
5Connections
Right now I'm focused on LiveReview, AI code review that gives teams control over AI-generated code without slowing them down.

Commenters (This Week)

6 comments
2 comments
2 comments

Contribute meaningful comments to climb the leaderboard and earn badges!