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
+7.3k Golang : Hue, Saturation and Value(HSV) with OpenCV example
+5.3k Gogland : Datasource explorer
+7.7k Golang : How to feed or take banana with Gorilla Web Toolkit Session package
+10.4k Golang : Select region of interest with mouse click and crop from image
+3.5k Java : Get FX sentiment from website example
+6.1k Golang & Javascript : How to save cropped image to file on server
+6.6k Golang : Experimental emojis or emoticons icons programming language
+14.6k Golang : Normalize unicode strings for comparison purpose
+5.3k Javascript : How to loop over and parse JSON data?
+40.9k Golang : How to count duplicate items in slice/array?
+9k Golang : Gonum standard normal random numbers example
+5.3k Golang : fmt.Println prints out empty data from struct