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)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我的数据无法存进链表里
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端