How to Fetch Return Value from a goroutine in Golang
Created
Modified
Channels
A channel is a communication mechanism that lets one goroutine send values to another goroutine.
Make a main.go file containing the following:
package main
import (
"fmt"
"time"
)
func main() {
c1 := make(chan int)
c2 := make(chan string)
go func() {
time.Sleep(2 * time.Second)
c1 <- 10
}()
go func() {
time.Sleep(time.Second)
c2 <- "One"
}()
// Fetch
for i := 0; i < 2; i++ {
// Await both of these values
// simultaneously, printing each one as it arrives.
select {
case m1 := <-c1:
fmt.Println("received ", m1)
case m2 := <-c2:
fmt.Println("received ", m2)
}
}
}
$ go run main.go received One received 10