Created
July 2, 2020 00:29
-
-
Save mwf/c214cae69df42d1257ba6655c5f92503 to your computer and use it in GitHub Desktop.
Merge channels in Golang
This file contains hidden or 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 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