doumao1519 2017-12-24 20:59
浏览 36
已采纳

Golang中的Reader如何在循环中自动迭代?

I'm reading about how to use CSVs in Golang and came across this code:

csvFile, _ := os.Open("people.csv")
reader := csv.NewReader(bufio.NewReader(csvFile))
var people []Person
for {
    line, error := reader.Read()
    if error == io.EOF {
        break
    } else if error != nil {
        log.Fatal(error)
    }
    people = append(people, Person{
        Firstname: line[0],
        Lastname:  line[1],
    })
}

Located here: https://www.thepolyglotdeveloper.com/2017/03/parse-csv-data-go-programming-language/

What I find confusing here is with the infinite for-loop, each iteration grabs the next line but there's no lineNum++ type logic being passed into the Reader. How does the reader know which iteration its on? How can I change this? E.g. grab just the first line.

  • 写回答

1条回答 默认 最新

  • dounie5475 2017-12-24 21:46
    关注

    How does a Reader in Golang automatically iterate in a loop? How does the reader know which iteration its on?

    The Read method returns the next record by consuming more data from the underlying io.Reader. The Read method returns io.EOF when there are no more records in the underlying reader.

    The application is responsible for calling read in a loop as shown in the example.

    The Reader does not need to know the line number to read the next record, but the Reader does maintain a line counter in its internal state for annotating errors.

    If the application needs to know the line number, the application can declare a counter and increment the counter on each read.

    How can I change this? E.g. grab just the first line.

    Call Read once:

    f, err := os.Open("people.csv")
    if err != nil {
        // handle error
    } 
    defer f.Close()
    
    r := csv.NewReader(f)
    firstLine, err := r.Read()
    if err != nil {
       // handle error
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用