grep() 함수
grep() 함수는 find() 함수 안에 있는 고루틴이 전달할 파일 목록을 in 채널로 전달받아서 필터링한 후 결과를 다시 out 채널로 전송한다.
import "regexp" func grep(pattern string, in <-chan string) <-chan string { out := make(chan string, cap(in)) go func() { regex, err := regexp.Compile(pattern) if err != nil { panic(err) } for file := range in { if regex.MatchString(file) { out <- file } } close(out) }() return out }
동작 방식은 find() 함수와 유사하다. 정규식으로 파일을 필터링하는 작업은 고루틴으로 동작하고, 필터링 결과는 out 채널을 통해 다음 단계로 전송된다. 이 작업은 in 채널이 닫힐 때까지 계속 진행된다.
필터링 작업도 대기 없이 연속으로 진행되도록 out 채널을 버퍼드 채널로 만들었다. 용량은 in 채널의 용량과 같게 맞췄다.