dongyang4615 2017-09-07 14:16
浏览 8
已采纳

如何在匿名函数中逐行扫描文件并将其向下传递到通道

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?

  • 写回答

1条回答 默认 最新

  • duandunzhuo3234 2017-09-07 14:24
    关注

    You're closing the file before you read it.

    You're only printing every other line.

    Move the defer into the closure where the reads actually happen.

    func reader(file string) <-chan string {
        out := make(chan string)
    
        f, err := os.Open(file)
        if err != nil {
            log.Fatal(err)
        }
    
        s := bufio.NewScanner(f)
        go func() {
            defer f.Close()
            defer close(out)
            for s.Scan() {
                out <- s.Text()
            }
            if err := s.Err(); err != nil {
                fmt.Println("error reading file:", err)
            }
        }()
    
        return out
    }
    

    Then print the value from the range clause, not a second value received within the for loop:

    func main() {
        out := reader(os.Args[1])
        for line := range out {
            fmt.Println(line)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!