package main
import "fmt"
type PipeFunc func(<-chan int) <-chan int
func Sq(ch <-chan int) <-chan int {
out := make(chan int)
go func() {
for val := range ch {
out <- val * val
}
close(out)
}()
return out
}
func Odd(ch <-chan int) <-chan int {
out := make(chan int)
go func() {
for val := range ch {
if val%2 != 0 {
out <- val
}
}
close(out)
}()
return out
}
func Sum(ch <-chan int) <-chan int {
out := make(chan int)
go func() {
sum := 0
for val := range ch {
sum += val
}
out <- sum
close(out)
}()
return out
}
func Pipeline(dataSource <-chan int, pipeFns ...PipeFunc) <-chan int {
for i := range pipeFns {
dataSource = pipeFns[i](dataSource)
}
return dataSource
}
func main() {
data := []int{1, 2, 3, 4, 5, 6, 6, 7, 8, 8, 9, 9, 0}
dataSource := make(chan int)
go func() {
for _, item := range data {
dataSource <- item
}
close(dataSource)
}()
resCh := Pipeline(dataSource, Sq, Odd, Sum)
for v := range resCh {
fmt.Println("result: ", v)
}
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結
用過哪些工具?為啥用這個工具(速度快,支援高併發...)?底層如何實現的?