Created
May 22, 2021 09:25
-
-
Save Yapcheekian/60542e7e276321b8d7631257613eef8e to your computer and use it in GitHub Desktop.
why nil channel is important
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" | |
"log" | |
"math/rand" | |
"time" | |
) | |
func main() { | |
a := asChan(1, 3, 5, 7) | |
b := asChan(2, 4, 6, 8) | |
c := merge(a, b) | |
for v := range c { | |
fmt.Println(v) | |
} | |
} | |
func asChan(v ...int) <-chan int { | |
c := make(chan int) | |
go func() { | |
for _, v := range v { | |
c <- v | |
time.Sleep(time.Duration(rand.Intn(1000)) * time.Millisecond) | |
} | |
close(c) | |
}() | |
return c | |
} | |
func merge(a, b <-chan int) <-chan int { | |
c := make(chan int) | |
go func() { | |
defer close(c) | |
for a != nil || b != nil { | |
select { | |
case v, ok := <-a: | |
if !ok { | |
// setting channel to nil will make this case to be disabled in the next iteration | |
a = nil | |
log.Printf("a is done") | |
continue | |
} | |
c <- v | |
case v, ok := <-b: | |
if !ok { | |
b = nil | |
log.Printf("b is done") | |
continue | |
} | |
c <- v | |
} | |
} | |
}() | |
return c | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment