## 4.13. 生成素数

``````  09    // Send the sequence 2, 3, 4, ... to channel 'ch'.
10    func generate(ch chan int) {
11        for i := 2; ; i++ {
12            ch <- i  // Send 'i' to channel 'ch'.
13        }
14    }
``````

``````  16    // Copy the values from channel 'in' to channel 'out',
17    // removing those divisible by 'prime'.
18    func filter(in, out chan int, prime int) {
19        for {
20            i := <-in  // Receive value of new variable 'i' from 'in'.
21            if i % prime != 0 {
22                out <- i  // Send 'i' to channel 'out'.
23            }
24        }
25    }
``````

``````          go sum(hugeArray); // calculate sum in the background
``````

``````          ch := make(chan int);
go sum(hugeArray, ch);
// ... do something else for a while
result := &lt;-ch;  // wait for, and retrieve, result
``````

``````  28    func main() {
29        ch := make(chan int)  // Create a new channel.
30        go generate(ch)  // Start generate() as a goroutine.
31        for {
32            prime := <-ch
33            fmt.Println(prime)
34            ch1 := make(chan int)
35            go filter(ch, ch1, prime)
36            ch = ch1
37        }
38    }
``````

29行先调用"generate"函数，用于产生最原始的自然数序列（从2开始）。然后 从输出管道读取的第一个数为新的素数，并以这个新的素数生成一个新的过滤器。 然后将新创建的过滤器添加到前一个过滤器后面，新过滤器的输出作为新的输出 管道。

sieve程序还可以写的更简洁一点。这里是"generate"的改进，代码在 "progs/sieve1.go"中：

``````  10    func generate() chan int {
11        ch := make(chan int)
12        go func(){
13            for i := 2; ; i++ {
14                ch <- i
15            }
16        }()
17        return ch
18    }
``````

``````  21    func filter(in chan int, prime int) chan int {
22        out := make(chan int)
23        go func() {
24            for {
25                if i := <-in; i % prime != 0 {
26                    out <- i
27                }
28            }
29        }()
30        return out
31    }
``````

``````  33    func sieve() chan int {
34        out := make(chan int)
35        go func() {
36            ch := generate()
37            for {
38                prime := <-ch
39                out <- prime
40                ch = filter(ch, prime)
41            }
42        }()
43        return out
44    }
``````

``````  46    func main() {
47        primes := sieve()
48        for {
49            fmt.Println(<-primes)
50        }
51    }
``````