Level up your GoLang concurrency skills by using channels to communicate and pass information between Go routines!

Go has risen to fame in large part due to its clean and efficient take on concurrency. We can use Go routines to run multiple threads in the background of our main program for a huge boost in efficiency. But how can we communicate between our go routines or share resources between them? Well prepare to be amazed by the simple yet powerful nature of channels in Go.

There’s no history lessons here, let’s dive straight into the code!

A simple example on channels:

While channels have greatly simplified concurrent programming, we still need to be careful with how we build our understanding of them. In the program below, we perform only four operations that we will step through.

The first step is to create our channel on line 7. We define the input to that channel to be of type string. Next, we create an anonymous function on lines 9 through 11 where we take the string "ping" and _send it to the channel _messages.

When working with channels, you can think of the _<-_ operation to be sending information to or from a channel depending on the direction of the arrow.

package main

import "fmt"

func main() {

    messages := make(chan string)

    go func() { 
		messages <- "ping" 

    msg := <-messages

The third step is to then ask for the stored string "ping" from the messages channel to the msg variable. The final step is to simply print that message out to the console.

#golang #programming #technology #tutorial

Orchestrate Your Go Routines Using Channels
1.50 GEEK