CSV Reader FieldsPerRecord Variable Rows
csv.Reader with FieldsPerRecord set to -1 accepts rows of any width, while the default mode rejects records that differ from the first row.
Code
package main
import (
"encoding/csv"
"fmt"
"io"
"strings"
)
func main() {
// rows with variable column counts: -1 disables the per-row width check
data := "id,name\n101,ada,admin\n102,lin\n"
r := csv.NewReader(strings.NewReader(data))
r.FieldsPerRecord = -1
for {
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
panic(err)
}
fmt.Printf("%d fields: %v\n", len(record), record)
}
// 默认模式:首行定宽,之后行宽不符整体报错
strict := csv.NewReader(strings.NewReader(data))
for {
record, err := strict.Read()
if err == io.EOF {
break
}
if err != nil {
fmt.Println("strict err:", err)
break
}
fmt.Println("strict row:", record)
}
}How the snippet works
The snippet is organized around the function main.
Iteration happens inside for — everything outside it runs once. Failure handling is panic(err): 2 checkpoints abort the program at the point a problem is detected.
Watch out for
- No third-party packages are used — the runtime ships every API called here.
panic(err)is the only failure path here: the first problem stops the program.
Putting it to use
Entry signature: func main()
The run prints labeled output — strict err:, strict row: — when the file runs.
The core lines of the flow
if err != nil {
panic(err)
}
if err != nil {
fmt.Println("strict err:", err)
break
}
Interactive Tools for This Topic
CSV Column AnalyzerProfile every CSV column with inferred types, empty-cell counts, unique values, and numeric min and max ranges.CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.CSV to Markdown TableConvert CSV data, including quoted fields with embedded commas and newlines, into a clean GitHub-flavored Markdown table with selectable alignment.CSV to TSV ConverterParse RFC 4180 CSV with quoted fields and re-serialize using a tab, pipe, semicolon, or custom delimiter, with optional quoting.
FAQ
- What happens when a call fails?
- There are no error returns here: a non-nil `err` reaches `panic(err)` immediately.
- What does CSV Reader FieldsPerRecord Variable Rows print when run?
- Running the file directly is enough — expect labeled output lines such as `strict err:`, `strict row:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.