Go is well known for it’s use of goroutines, the lightweight thread managed by the Go runtime. In the use of goroutines, we utilize channels.
Channels, Channels are a conduit through which you can send and receive values.
By default, sends and receives block until the other side is ready. This allows goroutines to synchronize without explicit locks or condition variables.
The example code sums the numbers in a slice, distributing the work between two goroutines. Once both goroutines have completed their computation, it calculates the final result.
How this looks
In this example, we start with a blank template: the normal package declaration, import statement for “fmt” only and a main function.
package main import ( "fmt" ) func main() { }
Next, we will create a channel, call a goroutine while passing our channel to the function, finally printing the value of our channel as set within the goroutine.
func main() { greeting := make(chan string) //create a channel go say(greeting) //call a goroutine which takes a channel as an argument fmt.Println(<- greeting) //print the value within our channel }
Then, we will create one function to write into our channel.
func say(greeting chan string) { greeting <- "Hello, World" }
The final code will appear as so
package main import ( "fmt" ) func say(greeting chan string) { greeting <- "Hello, World" } func main() { //create a channel greeting := make(chan string) //call a goroutine which takes a channel as an argument go say(greeting) //print the value within our channel fmt.Println(<- greeting) }
When you run the code you will see the output: Hello, World
I hope this was a helpful explanation of channels. Happy Coding!
A Web Developer by trade, future data scientist.
A motorcycle enthusiast at heart.
Most days I’d rather be in the woods anywhere.