Last active
January 17, 2023 15:23
-
-
Save 1ort/20a45f878c51ef7c75fc508f9c611551 to your computer and use it in GitHub Desktop.
Golang generic channel merging function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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