dongtangjie0495 2014-11-17 11:59
浏览 58
已采纳

哪个软件包在golang中包含合并功能

I am trying to merge 2 channels in an iteration so that I can retrieve both channels values for each step. I wrote the following lines

ch1, ch2 := make(chan int), make(chan int)
go Walk(t1, ch1)
go Walk(t2, ch2)

for ints := range merge(ch1, ch2) {
    fmt.Println(ints)
}

but when I run it, I get "prog.go:31: undefined: merge". I would like to know where this merge function is located.

  • 写回答

1条回答 默认 最新

  • dscss8996 2014-11-17 12:04
    关注

    There isn't such a function in the standard library, you'll have to define it yourself.

    From your code, it seems that you've read this post which already gives an example of merge, a user-defined function:

    func merge(cs ...<-chan int) <-chan int {
        var wg sync.WaitGroup
        out := make(chan int)
    
        // Start an output goroutine for each input channel in cs.  output
        // copies values from c to out until c is closed, then calls wg.Done.
        output := func(c <-chan int) {
            for n := range c {
                out <- n
            }
            wg.Done()
        }
        wg.Add(len(cs))
        for _, c := range cs {
            go output(c)
        }
    
        // Start a goroutine to close out once all the output goroutines are
        // done.  This must start after the wg.Add call.
        go func() {
            wg.Wait()
            close(out)
        }()
        return out
    }
    

    source: http://blog.golang.org/pipelines

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式