Both reader and writer have some options that can be changed after creation. Both structures share the Comma field, which is the character used for separating fields. Another important field that belongs to the writer only is FieldsPerRecord, which is an integer that determines how many fields the reader should expect for each record:
- If greater than 0, it will be the number of field required.
- If equal to 0 it will set to the number of field of the first record.
- If negative, all checks on the field count will be skipped, allowing for the reading of inconsistent sets of records.
Let's look at a practical example of a reader that is not checking for consistency and uses a space as a separator:
func main() {
r := csv.NewReader(strings.NewReader("a b\ne f g\n1"))
r.Comma = ' '
r.FieldsPerRecord = -1
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/KPHXRW5OxXT.