我不久前刚刚写了一个素数筛选法,http://studygolang.com/topics/556
基本是C语言的思路
不过今天我刚刚看到这个经典的CSP的代码
完全是 GO的风格!
http://tonybai.com/tag/go/page/2/
刚开始我没有看懂,自己运行一下,居然可以连续输出素数!
不由得我对这段代码兴趣大增!反复看,终于明白了它的执行过程,心中的高兴劲别提了!
好久没有这样兴奋过了!
开始仔细琢磨 GO的代码语境,真的很带劲的代码!
```golang
package main
import "fmt"
// Send the sequence 2, 3, 4, … to channel 'ch'.
func generate(ch chan<- int) {
for i := 2; ; i++ {
ch <- i // Send 'i' to channel 'ch'.
}
}
// Copy the values from channel 'src' to channel 'dst',
// removing those divisible by 'prime'.
func filter(src <-chan int, dst chan<- int, prime int) {
for i := range src { // Loop over values received from 'src'.
if i%prime != 0 {
dst <- i // Send 'i' to channel 'dst'.
}
}
}
// The prime sieve: Daisy-chain filter processes together.
func sieve() {
ch := make(chan int) // Create a new channel.
go generate(ch) // Start generate() as a subprocess.
for {
prime := <-ch
fmt.Print(prime, "\n")
ch1 := make(chan int)
go filter(ch, ch1, prime)
ch = ch1
}
}
func main() {
sieve()
}
```