Skip to content

struct: return error instead of panic when MapTo receives a nil pointer (fixes #369)#383

Open
nghiack7 wants to merge 2 commits into
go-ini:mainfrom
nghiack7:fix/mapTo-nil-pointer
Open

struct: return error instead of panic when MapTo receives a nil pointer (fixes #369)#383
nghiack7 wants to merge 2 commits into
go-ini:mainfrom
nghiack7:fix/mapTo-nil-pointer

Conversation

@nghiack7
Copy link
Copy Markdown

@nghiack7 nghiack7 commented May 9, 2026

Problem

Two related bugs in mapToField when the target is a nil pointer or a slice of struct pointers:

Both root causes are the same: mapToField only unwrapped one level of pointer indirection and never initialized nil pointers.

Fix

Replace the single if val.Kind() == reflect.Pointer block with a for loop that:

  1. Walks the full pointer chain (handles **T, ***T, etc.)
  2. Allocates any nil pointer via reflect.New (mirrors encoding/json behavior)
  3. Returns a clear error if the pointer cannot be set

Tests

Fixes #369, fixes #370

Nghĩa Nguyễn Ngọc added 2 commits May 9, 2026 14:54
Calling MapTo (or Section.MapTo) with a nil struct pointer caused a
panic in mapToField because val.Elem() on a nil pointer returns a zero
reflect.Value, and the subsequent val.Type() call on that zero value
triggers a runtime panic.

Add an IsValid check after the Pointer dereference and return a
descriptive error, matching the expected behaviour of the method
(returns error) instead of crashing the caller.

Fixes go-ini#369
…ter structs

- Change single if to for loop so chained/double pointers are fully dereferenced
- Auto-initialize nil pointers via reflect.New instead of returning an error
- Fixes go-ini#369 (nil pointer panic on MapTo) and go-ini#370 (slice of *Struct panic)

Previously mapToField would panic when encountering a nil pointer inside a
slice of struct pointers ([]*Peer pattern common in WireGuard-style configs).
The fix mirrors encoding/json behavior: walk the pointer chain, allocating
any nil links, then map into the concrete value.
@nghiack7
Copy link
Copy Markdown
Author

Friendly ping — this PR is ready for review. Fixes panics when MapTo receives a nil pointer or a slice of struct pointers (issues #369, #370). Tests pass ✅.

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.

panic: slice of struct pointers panic: nil struct pointer to MapTo

1 participant