package main
import (
"fmt"
)
func main() {
generator := func(done <-chan interface{},
args ...int) <-chan int {
results := make(chan int)
go func() {
defer close(results)
for _, v := range args {
select {
case <-done:
return
case results <- v:
}
}
}()
return results
}
multiply := func(done <-chan interface{},
intStream <-chan int,
multiplier int) <-chan int {
results := make(chan int)
go func() {
defer close(results)
for i := range intStream {
select {
case <-done:
return
case results <- i * multiplier:
}
}
}()
return results
}
add := func(done <-chan interface{},
intStream <-chan int,
additive int) <-chan int {
results := make(chan int)
go func() {
defer close(results)
for i := range intStream {
select {
case <-done:
return
case results <- i + additive:
}
}
}()
return results
}
done := make(chan interface{})
defer close(done)
for v := range multiply(done, add(done, multiply(done, generator(done, 1, 2, 3, 4), 2), 1), 2) {
fmt.Println(v)
}
}
程序输出如下,
有疑问加站长微信联系(非本文作者)