From 586c26740b2399691454a47b62ba904a4a9b6ee6 Mon Sep 17 00:00:00 2001 From: Dmitry Kargashin Date: Tue, 26 Sep 2023 05:33:16 +0300 Subject: [PATCH] fix: don't pass slice's defaultVal to setField func --- defaults.go | 2 +- defaults_test.go | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/defaults.go b/defaults.go index b5e7eb9..f453928 100644 --- a/defaults.go +++ b/defaults.go @@ -169,7 +169,7 @@ func setField(field reflect.Value, defaultVal string) error { } case reflect.Slice: for j := 0; j < field.Len(); j++ { - if err := setField(field.Index(j), defaultVal); err != nil { + if err := setField(field.Index(j), ""); err != nil { return err } } diff --git a/defaults_test.go b/defaults_test.go index 350ad62..b0dc0e7 100644 --- a/defaults_test.go +++ b/defaults_test.go @@ -144,6 +144,9 @@ type Sample struct { NonInitialSlice []int `default:"[123]"` NonInitialStruct Struct `default:"{}"` NonInitialStructPtr *Struct `default:"{}"` + + StructSliceWithEmptyDefaultElem []Struct `default:"[{}]"` + StructSliceWithFilledDefaultElem []Struct `default:"[{\"WithDefault\":\"changed\"}]"` } type Struct struct { @@ -680,6 +683,15 @@ func TestInit(t *testing.T) { t.Errorf("it should not initialize a struct with default values") } }) + + t.Run("slice of structs", func(t *testing.T) { + if !reflect.DeepEqual(sample.StructSliceWithEmptyDefaultElem, []Struct{{Embedded: Embedded{Int: 1}, Foo: 0, Bar: 456, WithDefault: "foo"}}) { + t.Errorf("it should automatically fill a slice of structs with elements from default") + } + if !reflect.DeepEqual(sample.StructSliceWithFilledDefaultElem, []Struct{{Embedded: Embedded{Int: 1}, Foo: 0, Bar: 456, WithDefault: "changed"}}) { + t.Errorf("it should overwrite child's default with parent's") + } + }) } func TestCanUpdate(t *testing.T) {