chan工厂
package mainimport ("fmt")func generate() chan int {out := make(chan int)go func() {for i := 2; ; i++ {out <- i}}()return out}func filter(in chan int, prime int) chan int {out := make(chan int)go func() {for {if v := <-in; v%prime != 0 {out <- v}}}()return out}func primeG() chan int {out := make(chan int)firstLine := generate()go func() {for {prime := <-firstLineout <- primenextLine := filter(firstLine, prime)firstLine = nextLine}}()return out}func main() {primes := primeG()for {prime := <-primesif prime < 100 {fmt.Println(prime)}}}
参数传递
package mainimport "fmt"func generate(in chan int) {for i := 2; ; i++ {in <- i}}func filter(in, out chan int, prime int) {for item := range in {if item%prime != 0 {out <- item}}}func main() {firstChan := make(chan int)go generate(firstChan)for {prime := <-firstChanif prime < 100 {fmt.Println(prime)}nextChan := make(chan int)go filter(firstChan, nextChan, prime)firstChan = nextChan}}