Golang: How To Implement Concurrency With Goroutines and Channels | by Axel Dietrich | Feb, 2022

Concurrency in Go is a whole lot simpler

Axel Dietrich
As we can see, goroutines are concurrency on steroids.
We are executing a goroutine
Done!
9
Process finished with the exit code 0

As their name tells us, are like two-ways streets for our data between goroutines. We have to initialize it with the function makethe keyword chan and the data type between parenthesis.

ch := make(chan dataType)
We are executing a goroutine
9
The result is: 9
Process finished with the exit code 0

Let’s make our timesThree function receive an array of number and iterate over it multiplying every element by three

We are executing a goroutine
The result is: 6
Process finished with the exit code 0
We are executing a goroutine
Result: 6
Result: 9
Result: 12
Process finished with the exit code 0

Another great feature is the possibility to execute an anonymous function as a goroutine, if we won’t reuse it. Note that we declare the function after the keyword go and we pass the parameters between parenthesis after the final curly brackets.

Channels not only work for interactions between a goroutine and the main programs, they also provide a way to communicate between different goroutine. For example, let’s create a function that subtracts 3 to every result returned by timesThree but only if it’s an even number.

We are executing a goroutine
The functions continues after returning the result
The functions continues after returning the result
Result: 3
Result: 9
Result: 9
Process finished with the exit code 0

Leave a Comment