Skip to content

Instantly share code, notes, and snippets.

@just1689
Last active April 8, 2018 11:19
Show Gist options
  • Save just1689/fdebaf76cba123555fcf4959acde1301 to your computer and use it in GitHub Desktop.
Save just1689/fdebaf76cba123555fcf4959acde1301 to your computer and use it in GitHub Desktop.
Merge data from multiple channels
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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment