美文网首页
golang 文件分类

golang 文件分类

作者: 夜空一起砍猩猩 | 来源:发表于2018-08-30 17:01 被阅读0次

    package main

    import (

        "fmt"

    )

    func files(fs []string) <-chan string{

        c := make(chan string, 1000) //带1000个缓冲的channel,1000个以内不会阻塞

        go func(){

            for _, f := range fs{

                c <- f

            }

            close(c)   //切片内所有文件发送完毕,关闭

        }()

        return c

    }

    func filterSize(in <-chan string) <-chan string{

        c := make(chan string, 1000)  //带1000个缓冲的channel,1000个以内不会阻塞

        go func (){

            for i := range in{

                fmt.Println("filter size got:", i)

                if i == "123.txt" || i == "456.txt"{

                    c <- i

                 }

        }

        close(c)

        }()

        return c

    }

    func main() {

        fmt.Println("file filter service")

        fs := []string{"123.txt","456.txt","789.txt","1222.txt"}

        c := filterSize(files(fs))

        for i := range c{ //阻塞main gorouting, 循环取channel中的数据,直到channel关闭

            fmt.Println("main got:", i)

        }

    }

    输出: 

    file filter service

    filter size func got: 123.txt

    filter size func got: 456.txt

    filter size func got: 789.txt

    filter size func got: 1222.txt

    main got: 123.txt

    main got: 456.txt

    相关文章

      网友评论

          本文标题:golang 文件分类

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