nil Channels
Let’s learn about nil channels.
We'll cover the following...
The use of nil
channels
nil
channels always block! Therefore, we should only use them when we actually want that behavior.
Coding example
The code that follows illustrates nil
channels:
Press + to interact
package mainimport ("fmt""math/rand""sync""time")var wg sync.WaitGroupfunc add(c chan int) {sum := 0t := time.NewTimer(time.Second)for {select {case input := <-c:sum = sum + inputcase <-t.C:c = nilfmt.Println(sum)wg.Done()}}}func send(c chan int) {for {c <- rand.Intn(10)}}func main() {c := make(chan int)rand.Seed(time.Now().Unix())wg.Add(1)go add(c)go send(c)wg.Wait()}
We are ...