Skip to content

Instantly share code, notes, and snippets.

@1ort
Last active January 17, 2023 15:23
Show Gist options
  • Save 1ort/20a45f878c51ef7c75fc508f9c611551 to your computer and use it in GitHub Desktop.
Save 1ort/20a45f878c51ef7c75fc508f9c611551 to your computer and use it in GitHub Desktop.
Golang generic channel merging function
package merge
func Merge[T any](cs ...<-chan T) <-chan T {
var wg sync.WaitGroup
out := make(chan T)
output := func(c <-chan T) {
for n := range c {
out <- n
}
wg.Done()
}
wg.Add(len(cs))
for _, c := range cs {
go output(c)
}
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