Go: Copy CSV records before the reader reuses them
Enabling csv.Reader.ReuseRecord can reduce slice allocations while processing a CSV stream. If you keep returned records for later, copy each one before the next read can overwrite its fields.
Set up
Tested on Linux amd64 with Go 1.26.10. Use Bash with Go on your PATH, a text editor, and the mktemp, rm, and rmdir utilities. The example uses only the standard library. Keep the same terminal through cleanup, and stop if setup fails before saving the source.
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save as go-csv-copy-reused-records.go:
package main
import (
"encoding/csv"
"fmt"
"io"
"slices"
"strings"
)
func collect(copyRecord bool) [][]string {
reader := csv.NewReader(strings.NewReader("tea,2\ncoffee,3\n"))
reader.FieldsPerRecord = 2
reader.ReuseRecord = true
var rows [][]string
for {
record, err := reader.Read()
if err == io.EOF {
break
}
if err != nil {
panic(err)
}
if copyRecord {
record = slices.Clone(record)
}
rows = append(rows, record)
}
return rows
}
func main() {
borrowed := collect(false)
owned := collect(true)
fmt.Printf("retained slices: %q\n", borrowed)
fmt.Printf("copied records: %q\n", owned)
owned[1][0] = "cocoa"
fmt.Printf("after editing second record: %q\n", owned)
if owned[0][0] != "tea" || owned[0][1] != "2" {
panic("first record changed")
}
}Run:
go run go-csv-copy-reused-records.goObserved output:
retained slices: [["coffee" "3"] ["coffee" "3"]]
copied records: [["tea" "2"] ["coffee" "3"]]
after editing second record: [["tea" "2"] ["cocoa" "3"]]Read the result
The first collection deliberately retains borrowed slices. With this input and tested implementation, both entries show the last record because the reader reused their backing array. The copied collection keeps the original product and quantity for each row.
slices.Clone copies the slice elements before the reader advances. Each element is a string, so copying these string values is enough to preserve the fields through later reads. The final assignment also checks that editing one retained record leaves the other unchanged.
Apply it carefully
Leave ReuseRecord at its default false when you need caller-owned records and have no measured reason to change it. With reuse enabled, finish consuming each record before the next read or clone it first. Clone it before sending it to a worker that may still be using it when the reader advances.
Reuse is permitted, not guaranteed on every read: record sizes and allocations can change. Do not make application logic depend on seeing the overwrite demonstrated here. The example rejects parse errors before retaining a row and fixes the field count at two; quantity validation is a separate step.
See the reader ownership contract and slice cloning reference.
Clean up
Remove the saved source and the empty scratch directory. Go manages its build cache separately. If the directory is not empty, inspect its contents before removing anything else.
rm -- go-csv-copy-reused-records.go
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirAcknowledgements
This post was created with assistance from AI.