go - 如何创建一个从 goroutine 接收多个返回值的 channel

标签 go

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

最佳答案

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

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

例如:

type Result struct {
    Field1 string
    Field2 int
}

然后

ch := make(chan Result)

使用自定义类型(Playground) channel 的示例:

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)
    }
}

生产:

LOREM , 5
IPSUM , 5
DOLOR , 5
SIT , 3
AMET , 4

编辑:使用多个 channel 而不是自定义类型来产生相同输出的示例 (Playground):

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)
    }
}

关于go - 如何创建一个从 goroutine 接收多个返回值的 channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17825857/

相关文章:

go - 如何配置 go 命令以使用代理?

unit-testing - 数据库单元测试

c++ - 如何在 go 中将 RGB byte[] slice 转换为 image.Image?

go - 使用 fan In 函数多路复用 Goroutine 输出

go - 使用不带命令的 PTY

go - sync.Map 是原子的吗?我主要是指加载、存储、加载或存储、删除

去安装但无法从 bin 以外的文件夹运行应用程序

golang 从 net.TCPConn 中以 4 个字节作为消息分隔读取字节

go - 如何使golang grpc客户端遵循重定向

go - 为什么不使用 go 1.10 编译器编译,但可以在 go playground 上运行