Explain the use of Go's goroutines for concurrent execution of code?

Goroutines are a powerful feature of Go that allow concurrent execution of code. A goroutine is a lightweight thread of execution that is managed by the Go runtime. Goroutines are cheap to create and have a small stack size, so it's possible to create many thousands of them. Goroutines are one of the key features of Go's support for concurrency.

To create a goroutine, you can use the **go** keyword followed by a function call. For example:

go myFunction()

This will create a new goroutine that runs **myFunction()** concurrently with the main program.

Goroutines can communicate with each other using channels. Channels are a typed conduit for passing messages between goroutines. Channels can be used to synchronize access to shared data or to coordinate the execution of multiple goroutines.

Here's an example of using goroutines and channels to implement a simple concurrent program that calculates the sum of the squares of a list of numbers:

package main

import "fmt"

func main() {
    numbers := []int{1, 2, 3, 4, 5}
    results := make(chan int)

    for _, n := range numbers {
        go func(x int) {
            results <- x * x

    sum := 0
    for i := 0; i < len(numbers); i++ {
        sum += <-results

    fmt.Println("Sum of squares:", sum)

In this program, we create a channel called **results** to hold the results of the square calculation. We then launch a goroutine for each number in the **numbers** slice. Each goroutine calculates the square of its assigned number and sends the result back to the **results** channel.

Finally, we read the results from the channel and add them up to get the total sum of squares. The use of goroutines and channels allows the calculation to be done concurrently, which can lead to significant performance improvements for large datasets.

Related Questions You Might Be Interested