package main
import (
"fmt"
"math/rand"
)
func main() {
repeatfn := func(
done <-chan interface{},
fn func() interface{},
) <-chan interface{} {
valueStream := make(chan interface{})
go func() {
defer close(valueStream)
for {
for {
select {
case <-done:
return
case valueStream <- fn():
}
}
}
}()
return valueStream
}
take := func(
done <-chan interface{},
valueStream <-chan interface{},
num int,
) <-chan interface{} {
takeStream := make(chan interface{})
go func() {
defer close(takeStream)
for i := 0; i < num; i++ {
select {
case <-done:
return
case takeStream <- <-valueStream:
}
}
}()
return takeStream
}
done := make(chan interface{})
defer close(done)
rand := func() interface{} { return rand.Int() }
for num := range take(done, repeatfn(done, rand), 10) {
fmt.Printf("%v \n", num)
}
fmt.Println()
}
程序输出如下,
image.png
网友评论