From 748ccaba3909081357d950dad0cbc69bf92bfa6e Mon Sep 17 00:00:00 2001 From: Yanhu007 Date: Mon, 13 Apr 2026 12:39:32 +0800 Subject: [PATCH] fix: return error instead of panicking when MapTo receives a nil pointer When MapTo is called with a pointer to a nil struct pointer (e.g. MapTo(&nilPtr)), the code dereferences the pointer once and then operates on the nil value, causing a panic. Add a loop to handle nested pointer types, returning a clear error message when a nil pointer is encountered. Fixes #369 --- struct.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/struct.go b/struct.go index a486b2f..7d9c058 100644 --- a/struct.go +++ b/struct.go @@ -388,6 +388,15 @@ func (s *Section) mapTo(v interface{}, isStrict bool) error { return errors.New("not a pointer to a struct") } + // Handle pointer-to-pointer: dereference again and check for nil + for val.Kind() == reflect.Ptr { + if val.IsNil() { + return errors.New("cannot map to a nil pointer") + } + typ = typ.Elem() + val = val.Elem() + } + if typ.Kind() == reflect.Slice { newField, err := s.mapToSlice(s.name, val, isStrict) if err != nil {