From 0575c4de745b8ea63a4e569ac2c0656ca2375cf6 Mon Sep 17 00:00:00 2001
From: Yanhu007
Date: Tue, 14 Apr 2026 12:44:26 +0800
Subject: [PATCH] fix: support pointer slices in nonunique section mapping
When a struct field is a slice of struct pointers (e.g. []*Peer),
mapToSlice used reflect.New on the pointer type, creating a **Peer.
mapToField only dereferences one level, causing a panic.
Detect when the slice element type is a pointer, allocate the
underlying struct type, and append the pointer to the slice.
Fixes #370
---
struct.go | 13 +++++++++++--
1 file changed, 11 insertions(+), 2 deletions(-)
diff --git a/struct.go b/struct.go
index a486b2f..f77f562 100644
--- a/struct.go
+++ b/struct.go
@@ -366,13 +366,22 @@ func (s *Section) mapToSlice(secName string, val reflect.Value, isStrict bool) (
}
typ := val.Type().Elem()
+ isPtr := typ.Kind() == reflect.Ptr
for i, sec := range secs {
- elem := reflect.New(typ)
+ elemTyp := typ
+ if isPtr {
+ elemTyp = typ.Elem()
+ }
+ elem := reflect.New(elemTyp)
if err = sec.mapToField(elem, isStrict, i, sec.name); err != nil {
return reflect.Value{}, fmt.Errorf("map to field from section %q: %v", secName, err)
}
- val = reflect.Append(val, elem.Elem())
+ if isPtr {
+ val = reflect.Append(val, elem)
+ } else {
+ val = reflect.Append(val, elem.Elem())
+ }
}
return val, nil
}