如何创建一个从 goroutine 接收多个返回值的通道

2024-02-10

我在 Go 中有一个返回两个值的函数。我想将其作为 goroutine 运行,但我无法弄清楚创建接收两个值的通道的语法。有人能指出我正确的方向吗?


定义一个包含两个值字段的自定义类型,然后创建一个chan那种类型的。

编辑:我还添加了一个使用多个通道而不是自定义类型的示例(位于底部)。我不确定哪个更惯用。

例如:

type Result struct {
    Field1 string
    Field2 int
}

then

ch := make(chan Result)

使用自定义类型通道的示例 (操场 http://play.golang.org/p/2WmxcQ0OeC):

package main

import (
    "fmt"
    "strings"
)

type Result struct {
    allCaps string
    length  int
}

func capsAndLen(words []string, c chan Result) {
    defer close(c)
    for _, word := range words {
        res := new(Result)
        res.allCaps = strings.ToUpper(word)
        res.length = len(word)
        c <- *res       
    }
}

func main() {
    words := []string{"lorem", "ipsum", "dolor", "sit", "amet"}
    c := make(chan Result)
    go capsAndLen(words, c)
    for res := range c {
        fmt.Println(res.allCaps, ",", res.length)
    }
}

生产:

洛雷姆, 5
伊普苏姆, 5
多洛尔, 5
坐, 3
阿美特, 4

编辑:使用多个通道而不是自定义类型来产生相同输出的示例(操场 http://play.golang.org/p/ocvGsen3gw):

package main

import (
    "fmt"
    "strings"
)

func capsAndLen(words []string, cs chan string, ci chan int) {
    defer close(cs)
    defer close(ci)
    for _, word := range words {
        cs <- strings.ToUpper(word)
        ci <- len(word)
    }
}

func main() {
    words := []string{"lorem", "ipsum", "dolor", "sit", "amet"}
    cs := make(chan string)
    ci := make(chan int)
    go capsAndLen(words, cs, ci)
    for allCaps := range cs {
        length := <-ci
        fmt.Println(allCaps, ",", length)
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何创建一个从 goroutine 接收多个返回值的通道 的相关文章