Skip to content

Skip nil pointer elements when encoding a slice or array - #77

Open
youdie006 wants to merge 1 commit into
jszwec:masterfrom
youdie006:skip-nil-pointer-elements
Open

youdie006 wants to merge 1 commit into
jszwec:masterfrom
youdie006:skip-nil-pointer-elements

Conversation

@youdie006

Copy link
Copy Markdown

Description

Marshal and Encoder.Encode panic on a []*T or [N]*T that contains a nil element: encodeArray passes the zero reflect.Value from walkValue to encodeStruct, which calls v.Type(). Unmarshal into [N]*T leaves the elements past the last record nil (as TestUnmarshal expects), so a round trip crashes:

var users [3]*User
csvutil.Unmarshal([]byte("Name,Age\nalice,30\nbob,25\n"), &users)
csvutil.Marshal(users)
// panic: reflect: call of reflect.Value.Type on zero Value

With this change a nil element writes no record, so the example returns "Name,Age\nalice,30\nbob,25\n", the same CSV it was decoded from. Writing an empty row or returning an InvalidEncodeError would also work if you prefer either; skipping is the one that round-trips.

Checklist

  • Code compiles without errors
  • Added new tests for the provided functionality
  • All tests are passing (go test -race ./...; the new cases panic on master)
  • Updated the README and/or documentation, if necessary

Written with AI assistance (Claude); I have reviewed the change.

encodeArray passed walkValue's zero Value for a nil *T element to
encodeStruct, which panicked in reflect.Value.Type. Unmarshal into [N]*T
leaves the elements past the last record nil, so Marshal of that value
panicked. A nil element now writes no record.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant