I want to write a function that reads lines from a file and sends then into a channel for further processing. I'm new to Go and here is the reader function I came up with following mostly textbook examples:
func reader(file string) <-chan string {
out := make(chan string)
f, err := os.Open(file)
if err != nil {
log.Fatal(err)
}
defer f.Close()
s := bufio.NewScanner(f)
go func() {
for s.Scan() {
out <- s.Text()
}
close(out)
}()
return out
}
In the main()
function I pass a file pointer into the reader function and try to drain the out channel as follows:
func main() {
out := reader(*f)
for range out {
fmt.Println(<-out)
}
}
I get no comilation or runtime errors, however, the output is empty. If I don't put the for loop into a goroutine I can print the file from withing the reader()
function w/o any problems.
I've furthermore tried to pass the Scanner, channel or both in the reader()
function into the anonymous function. But it didn't solve the problem. Can anyone explain please why this code does not work and how to remedy it?