I am trying to understand how the golang channel works. I read a book about go language and found the following example.
package main import ( "fmt" ) // Send the sequence 2, 3, 4, ... to returned channel func generate() chan int { ch := make(chan int) go func() { for i := 2; i <= 100 ; i++ { ch <- i } }() return ch } // Filter out input values divisible by 'prime', send rest to returned channel func filter(in chan int, prime int) chan int { out := make(chan int) go func() { for { if i := <-in; i%prime != 0 { out <- i } } }() return out } func sieve() chan int { out := make(chan int) go func() { ch := generate() for { prime := <-ch ch = filter(ch, prime) out <- prime } }() return out } func main() { primes := sieve() for { fmt.Println(<-primes) } }
When I run this program, I have a dead end, but when I change the generation function to
// Send the sequence 2, 3, 4, ... to returned channel func generate() chan int { ch := make(chan int) go func() { for i := 2; ; i++ { ch <- i } }() return ch }
Then the program will start an infinite loop, but not a dead end. Why do I get a dead end when I delete a condition in a for loop?
source share