Wrapping Goroutines to Handle Return Values in Go
Introduction
Concurrency is one of Go’s superpowers, enabling developers to run tasks in parallel using goroutines. A goroutine is launched with the go keyword followed by a function call, as shown below:
package main
import (
"fmt"
"time"
)
func say(s string) {
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s)
}
}
func main() {
go say("world")
say("hello")
}
Go playground link to the example
This simple example prints “hello” and “world” concurrently. However, the Go language specification notes that if a function called in a goroutine returns values, those values are discarded. This raises a question: how can we capture and use return values from a goroutine?