美文网首页
Repeat function

Repeat function

作者: FredricZhu | 来源:发表于2019-06-17 11:48 被阅读0次
    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

    相关文章

      网友评论

          本文标题:Repeat function

          本文链接:https://www.haomeiwen.com/subject/tuxafctx.html