Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which package contains merge function in golang

Tags:

go

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.

like image 698
P. Ekouaghe Avatar asked Dec 12 '22 02:12

P. Ekouaghe


1 Answers

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

like image 199
Agis Avatar answered Jan 07 '23 15:01

Agis