encoding/csv

encoding/csv Reader and Writer, including FieldsPerRecord, ErrFieldCount, Flush, and the aliasing that ReuseRecord can cause.

The encoding/csv package reads and writes RFC 4180 CSV. NewWriter buffers records; official documentation says you should call Flush when all data has been written and then check Writer.Error. NewReader accepts an io.Reader, so the examples use strings.NewReader and do not open files. They were checked with Go 1.24.0.

FieldsPerRecord controls field counts. The default 0 sets the expected count from the first record and treats a later mismatch as an error. A negative value disables the check. ReuseRecord, when true, lets later Read calls reuse the backing array of an earlier record.

Examples were checked against Go 1.24.0. See the official package documentation for the complete API.

Go reference overview →

API index

APISummary
csv.NewWriter, Writer.Write, Writer.Flush, csv.NewReader, Reader.Read, Reader.ReadAllWrite quoted CSV, then read it back with a field-count check. A mismatch still returns the record, together with ErrFieldCount.
Reader.Read, Reader.ReuseRecordWhen ReuseRecord is true, a later Read can overwrite the backing array of a slice you still hold from an earlier Read.

Writer, field counts, and ErrFieldCount

A field that contains a comma is quoted on write. After Flush, the writer output in the example is the two records terminated by newlines. On read, the default FieldsPerRecord of 0 takes the first record as the expected width. Official documentation says that if a later record has an unexpected number of fields, Read returns that record along with ErrFieldCount. The error is a *ParseError whose unwrap is csv.ErrFieldCount; errors.Is reports true for that sentinel. Setting FieldsPerRecord to -1 accepts rows of different widths, as ReadAll shows here.

csv.NewWriter, Writer.Write, Writer.Flush, csv.NewReader, Reader.Read, Reader.ReadAll

func NewWriter(w io.Writer) *Writer
func (w *Writer) Write(record []string) error
func (w *Writer) Flush()
func (w *Writer) Error() error
func NewReader(r io.Reader) *Reader
func (r *Reader) Read() (record []string, err error)
func (r *Reader) ReadAll() (records [][]string, err error)

Write quoted CSV, then read it back with a field-count check. A mismatch still returns the record, together with ErrFieldCount.

ParameterDescription
w / rAn io.Writer or io.Reader. The example uses a bytes.Buffer and strings.Reader, not a user file.
FieldsPerRecord0 (the default) locks the width to the first record. A positive value requires that many fields. A negative value disables the check.

Returns: Write returns an error from the underlying writer, if any. Flush has no result; check Error afterwards. Read returns the record and an error; at the end of the input, the error is io.EOF. ReadAll returns every record or the first error.

Errors

  • csv.ErrFieldCount — Returned, wrapped in a *ParseError, when the record width does not match FieldsPerRecord. Official documentation: Read still returns the record. The measured Error text on Go 1.24.0 is "record on line 2: wrong number of fields".
  • The quoted output "a,b",c was measured on Go 1.24.0 with the default comma delimiter and a trailing newline after each record.
go
package main

import (
	"bytes"
	"encoding/csv"
	"errors"
	"fmt"
	"strings"
)

func main() {
	var buf bytes.Buffer
	w := csv.NewWriter(&buf)
	_ = w.Write([]string{"a,b", "c"})
	_ = w.Write([]string{"d", "e"})
	w.Flush()
	fmt.Print(buf.String())
	fmt.Println(w.Error())

	r := csv.NewReader(strings.NewReader("a,b\n1,2,3\n"))
	rec, err := r.Read()
	fmt.Println(rec, err)
	rec, err = r.Read()
	fmt.Println(rec, err)
	fmt.Println(errors.Is(err, csv.ErrFieldCount))

	flexible := csv.NewReader(strings.NewReader("a,b\n1,2,3\n"))
	flexible.FieldsPerRecord = -1
	all, err := flexible.ReadAll()
	fmt.Println(all, err)
}

Expected output

"a,b",c
d,e
<nil>
[a b] <nil>
[1 2 3] record on line 2: wrong number of fields
true
[[a b] [1 2 3]] <nil>

Official documentation →

ReuseRecord

By default, each Read returns newly allocated memory owned by the caller, so a slice you kept from an earlier call still holds the earlier fields. If ReuseRecord is true, official documentation says the slice returned by Read may share backing storage between calls. In the example, after the second Read the slice saved from the first call now holds c, d, the same values as the second record. Copy the fields if you need to keep an earlier record while ReuseRecord is set.

Reader.Read, Reader.ReuseRecord

func (r *Reader) Read() (record []string, err error)

When ReuseRecord is true, a later Read can overwrite the backing array of a slice you still hold from an earlier Read.

ParameterDescription
ReuseRecordA field on Reader. If true, Read may reuse the previous record slice. The default is false.

Returns: The next record, or nil and io.EOF when the input is exhausted.

  • The shared-backing result was measured on Go 1.24.0: after the second Read, both variables print [c d]. With the default setting, the first variable still prints [a b].
go
package main

import (
	"encoding/csv"
	"fmt"
	"strings"
)

func main() {
	reused := csv.NewReader(strings.NewReader("a,b\nc,d\n"))
	reused.ReuseRecord = true
	first, _ := reused.Read()
	fmt.Println(first)
	second, _ := reused.Read()
	fmt.Println(first, second)

	fresh := csv.NewReader(strings.NewReader("a,b\nc,d\n"))
	a, _ := fresh.Read()
	b, _ := fresh.Read()
	fmt.Println(a, b)
}

Expected output

[a b]
[c d] [c d]
[a b] [c d]

Official documentation →