I have the following code:
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan int)
ch2 := make(chan int)
go func(c chan int, c2 chan int) {
for {
select {
case v := <-c:
fmt.Println(v)
case v := <-c2:
fmt.Println(v)
default:
}
}
}(ch, ch2)
ch <- 1
close(ch)
close(ch2)
time.Sleep(10 * time.Second)
}
When I run this, it prints 1
to the stdout, and then keeps printing 0
. Why is this?
I know I can check whether the channel is closed in my goroutine, but I just want to know the reason for this.
Also, suppose I want to exit from a goroutine after all(multiple) channels are closed, is that possible? I was assuming that once all channels are closed, I could potentially exit from the goroutine in the default case after all channels are closed