如何拿到多个goroutine的返回值,如何区别他们

题目来源: 映客

答案1:

go语言在执行goroutine的时候、是没有返回值的、这时候我们要用到go语言中特色的channel来获取返回值。
通过channel拿到返回值有两种处理方式,一种形式是具有go风格特色的,即发送给一个for channel 或 select channel 的独立goroutine中,由该独立的goroutine来处理函数的返回值。还有一种传统的做法,就是将所有goroutine的返回值都集中到当前函数,然后统一返回给调用函数。

使用channel比较符合go风格,举个一个例子

使用自定义channel类型

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. type Result struct {
  7. allCaps string
  8. length int
  9. }
  10. func capsAndLen(words []string, c chan Result) {
  11. defer close(c)
  12. for _, word := range words {
  13. res := new(Result)
  14. res.allCaps = strings.ToUpper(word)
  15. res.length = len(word)
  16. c <- *res // 写 channel
  17. }
  18. }
  19. func main() {
  20. words := []string{"lorem", "ipsum", "dolor", "sit", "amet"}
  21. c := make(chan Result)
  22. go capsAndLen(words, c) // 启动goroutine
  23. for res := range c {
  24. fmt.Println(res.allCaps, ",", res.length)
  25. }
  26. }

参考资料

https://stackoverflow.com/questions/17825857/how-to-make-a-channel-that-receive-multiple-return-values-from-a-goroutine