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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With