Skip to content

Instantly share code, notes, and snippets.

@mwf
Created July 2, 2020 00:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mwf/c214cae69df42d1257ba6655c5f92503 to your computer and use it in GitHub Desktop.
Save mwf/c214cae69df42d1257ba6655c5f92503 to your computer and use it in GitHub Desktop.
Merge channels in Golang
package main
import (
"fmt"
)
// merge prints stuff from two channels.
//
// This example is a friendly reminder, that closed channel still produces events in loop.
// https://play.golang.org/p/6TwGnvyvhQC
func merge(one, two chan int) {
oneClosed := false
twoClosed := false
for {
select {
case res, ok := <-one:
if !ok {
oneClosed = true
fmt.Println("one closed")
break
}
fmt.Println("old ", res)
case res, ok := <-two:
if !ok {
twoClosed = true
fmt.Println("two closed")
break
}
fmt.Println("new ", res)
}
if oneClosed && twoClosed {
fmt.Println("done")
return
}
}
}
func main() {
fmt.Println("Hello, playground")
one := make(chan int, 10)
one <- 1
one <- 2
one <- 3
close(one)
two := make(chan int, 10)
two <- 1
two <- 2
two <- 3
two <- 4
two <- 5
close(two)
merge(one, two)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment