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

时间:2014-11-17 11:59:30

标签: go

我试图在迭代中合并2个通道,以便我可以检索每个步骤的两个通道值。 我写了以下几行

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

但是当我运行它时,我得到“prog.go:31:undefined:merge”。 我想知道这个合并功能的位置。

1 个答案:

答案 0 :(得分:10)

标准库中没有这样的功能,您必须自己定义。

从您的代码中,您似乎已阅读this post已经提供了merge的示例,这是一个用户定义的函数:

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
}

来源:http://blog.golang.org/pipelines

相关问题