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