Golang : How to capture return values from goroutines?
Got a question asked by a newbie on Facebook yesterday. Her question was how to capture the return values generated by goroutines.
Alright, the simplest way to capture the output generated by goroutines is to use channels. The sample Golang code below demonstrate how to use channels to capture the return values.
package main
import "fmt"
func say(msg chan<- string) {
msg <- "Hello, 世界!"
}
// return multiple values, in this case it is 2
func trueOrFalse(answer chan<- bool) {
answer <- true
answer <- false
}
func main() {
messageChannel := make(chan string)
// execute Gorountine and return the value into messageChannel
go say(messageChannel)
fmt.Println(<-messageChannel)
// the channel has type. To receive 2 boolean values, we use increase it by 2
booleanChannel := make(chan bool, 2)
go trueOrFalse(booleanChannel)
fmt.Println(<-booleanChannel) // true
fmt.Println(<-booleanChannel) // false -- and also pop the stack
}
Output:
Hello, 世界!
true
false
References :
https://socketloop.com/tutorials/golang-channels-and-buffered-channels-examples
https://socketloop.com/tutorials/golang-concurrency-and-goroutine
See also : Golang : Channels and buffered channels examples
By Adam Ng(黃武俊)
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+5.5k Unix/Linux : Get reboot history or check when was the last reboot date
+7.3k Gogland : Single File versus Go Application Run Configurations
+8.3k Android Studio : Import third-party library or package into Gradle Scripts
+11.4k Golang : How to detect a server/machine network interface capabilities?
+11.7k Golang : Convert a rune to unicode style string \u
+30.6k error: trying to remove "yum", which is protected
+7.6k Golang : Scan files for certain pattern and rename part of the files
+10.6k Golang : Removes punctuation or defined delimiter from the user's input
+15.4k Golang : Get current time from the Internet time server(ntp) example
+27.1k Golang : dial tcp: too many colons in address
+14.4k Golang : Get URI segments by number and assign as variable example