Decoding values

Go allows users to create a CSV reader from any io.Reader. It is possible to read records one by one using the Read method:

func main() {
r := csv.NewReader(strings.NewReader("a,b,c\ne,f,g\n1,2,3"))
for {
r, err := r.Read()
if err != nil {
log.Fatal(err)
}
log.Println(r)
}
}

A full example of the preceding code is available at https://play.golang.org/p/wZgVzMqAN_K.

Note that each record is a string slice and the reader is expecting the length of each row to be consistent. If a row has more or fewer entries than the first, this will result in an error. It is also possible to read all records at once using ReadAll. The same example from before using such a method will look like this:

func main() {
r := csv.NewReader(strings.NewReader("a,b,c\ne,f,g\n1,2,3"))
records, err := r.ReadAll()
if err != nil {
log.Fatal(err)
}
for _, r := range records {
log.Println(r)
}
}

A full example of the preceding code is available at https://play.golang.org/p/RJ-wxBB5fs6.