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 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献