英文:
Which package contains merge function in golang
问题
我正在尝试在迭代中合并两个通道,以便可以在每个步骤中检索两个通道的值。
我写了以下代码:
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"的错误。
我想知道这个merge函数在哪里。
英文:
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
得分: 13
标准库中没有这样的函数,你需要自己定义它。
从你的代码来看,似乎你已经阅读了这篇文章,其中已经给出了一个名为merge的用户定义函数的示例:
func merge(cs ...<-chan int) <-chan int {
    var wg sync.WaitGroup
    out := make(chan int)
    // 为每个输入通道启动一个输出 goroutine。output 从 c 复制值到 out,直到 c 关闭,然后调用 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)
    }
    // 启动一个 goroutine,在所有输出 goroutine 完成后关闭 out。这必须在 wg.Add 调用之后启动。
    go func() {
        wg.Wait()
        close(out)
    }()
    return out
}
来源:http://blog.golang.org/pipelines
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论