Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12111

How can I launch several goroutines and obtain the result of each one separately?

$
0
0

I'm a little confused about the best way to use channels in Go. I am in a situation like this:

I need to execute the generateFruit, generateCity, generateCountry functions in 3 goroutines (each one in a goroutine) and then in main do something with those 3 results (but I need to know the result of each thing it corresponds to, that is, I need the result of the fruit, the city and the country. Likewise, I must know if an error occurred in any of them (I am not interested in knowing separately where the error came from)

package mainimport ("errors""math/rand""time")func generateFruit() (string, error) {    time.Sleep(1 * time.Second)    is_error := rand.Int() % 2    if is_error == 0 {        return "banana", nil    } else {        return "", errors.New("Some error")    }}func generateCity() (string, error) {    time.Sleep(1 * time.Second)    is_error := rand.Int() % 2    if is_error == 0 {        return "toronto", nil    } else {        return "", errors.New("Some error")    }}func generateCountry() (string, error) {    time.Sleep(1 * time.Second)    is_error := rand.Int() % 2    if is_error == 0 {        return "colombia", nil    } else {        return "", errors.New("Some error")    }}func main() {// Here}

Viewing all articles
Browse latest Browse all 12111

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>