*File vs bufio.NewReader(csvFile)

I am at the very beginning with learning golang.

I was trying to solve problem at : https://gophercises.com/exercises/quiz, i was able to solve that but have couple of questions.

  1. What’s good practice (idomatic way) to read CSV file?, What’s difference in below two ways?.
csvFile, _ := os.Open("problems.csv")
reader := csv.NewReader(bufio.NewReader(csvFile))


csvFile, _ := os.Open("problems.csv")
reader := csv.NewReader(csvFile)
1 Like

Using bufio.NewReader will behind the scenes call bufio.NewReaderSize which hash this documentation:

// NewReaderSize returns a new Reader whose buffer has at least the specified
// size. If the argument io.Reader is already a Reader with large enough
// size, it returns the underlying Reader.

So if there is any difference depends on the io.Reader returned by os.Open. If the buffer of it is ‘large enought’, there is no difference. The default buffer size is 4096.

whats the idiomatic way?

It depends on if you really need a buffered reader.

csv.NewReader is expecting a “normal” io.Reader, so it does not require you to create a buffered reader.

A buffered reader has some memory overhead, which I’d try to avoid unless I really need it.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.