From d9fe18f9ea676ead4c3e80df79acb828c414a6d1 Mon Sep 17 00:00:00 2001 From: Nash Aschenbath Date: Tue, 24 Nov 2026 23:49:36 +0800 Subject: [PATCH] Skip nil StructReflector fields before calling their method --- struct.go | 10 ++++---- struct_nil_reflector_test.go | 45 ++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 5 deletions(-) create mode 100644 struct_nil_reflector_test.go diff --git a/struct.go b/struct.go index 2fcd025..c370a4e 100644 --- a/struct.go +++ b/struct.go @@ -749,6 +749,11 @@ func (s *Section) encodeStruct(val reflect.Value, path []reflect.Type) error { continue } + // A nil pointer has nothing to write, including a StructReflector. + if field.Kind() == reflect.Pointer && field.IsNil() { + continue + } + if r, ok := field.Interface().(StructReflector); ok { if err := r.ReflectINIStruct(s.f); err != nil { return err @@ -761,11 +766,6 @@ func (s *Section) encodeStruct(val reflect.Value, path []reflect.Type) error { continue } - // A nil pointer has nothing to write. - if field.Kind() == reflect.Pointer && field.IsNil() { - continue - } - isStruct := isStructType(tpField.Type) isStructPtr := tpField.Type.Kind() == reflect.Pointer && isStructType(tpField.Type.Elem()) structType := tpField.Type diff --git a/struct_nil_reflector_test.go b/struct_nil_reflector_test.go new file mode 100644 index 0000000..927dd85 --- /dev/null +++ b/struct_nil_reflector_test.go @@ -0,0 +1,45 @@ +package ini + +import ( + "bytes" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type optionalReflector struct { + Value string +} + +func (r *optionalReflector) ReflectINIStruct(f *File) error { + f.Section("custom").Key("value").SetValue(r.Value) + return nil +} + +func TestReflectFrom_NilStructReflector(t *testing.T) { + for _, tc := range []struct { + name string + reflector *optionalReflector + want string + }{ + {name: "nil", want: "After = kept\n"}, + {name: "non-nil", reflector: &optionalReflector{Value: "present"}, + want: "After = kept\n\n[custom]\nvalue = present\n"}, + } { + t.Run(tc.name, func(t *testing.T) { + f := Empty() + in := struct { + Optional *optionalReflector + After string + }{Optional: tc.reflector, After: "kept"} + require.NotPanics(t, func() { + require.NoError(t, f.ReflectFrom(&in)) + }) + var buf bytes.Buffer + _, err := f.WriteTo(&buf) + require.NoError(t, err) + assert.Equal(t, tc.want, buf.String()) + }) + } +}