doujiao1905 2013-07-24 05:27 采纳率: 100%
浏览 621
已采纳

如何使通道从goroutine接收多个返回值

I have a function in Go that returns two values. I want to run this as a goroutine, but I can't figure out the syntax for creating a channel that receives two values. Could someone point me in the right direction?

  • 写回答

2条回答 默认 最新

  • doubu1950 2013-07-24 05:35
    关注

    Define a custom type with fields for both values, then create a chan of that type.

    EDIT: I've also added an example (right at the bottom) that uses multiple channels rather than a custom type. I'm not sure which is more idiomatic.

    For example:

    type Result struct {
        Field1 string
        Field2 int
    }
    

    then

    ch := make(chan Result)
    

    Example of using a channel of a custom type (Playground):

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

    Produces:

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

    EDIT: Example using multiple channels instead of a custom type to produce the same output (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)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择