Skip to content

Instantly share code, notes, and snippets.

@Yapcheekian
Created May 22, 2021 09:25
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 Yapcheekian/60542e7e276321b8d7631257613eef8e to your computer and use it in GitHub Desktop.
Save Yapcheekian/60542e7e276321b8d7631257613eef8e to your computer and use it in GitHub Desktop.
why nil channel is important
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