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.

GoData Integrity

Code

gosnippet
40 lines
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

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:`.