Skip to content

Commit abebf4b

Browse files
authored
Merge pull request #46 from orangejohny/master
fix: error when trying initialize slice of structs with `default` tag
2 parents 5220e08 + 586c267 commit abebf4b

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

defaults.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ func setField(field reflect.Value, defaultVal string) error {
169169
}
170170
case reflect.Slice:
171171
for j := 0; j < field.Len(); j++ {
172-
if err := setField(field.Index(j), defaultVal); err != nil {
172+
if err := setField(field.Index(j), ""); err != nil {
173173
return err
174174
}
175175
}

defaults_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,9 @@ type Sample struct {
144144
NonInitialSlice []int `default:"[123]"`
145145
NonInitialStruct Struct `default:"{}"`
146146
NonInitialStructPtr *Struct `default:"{}"`
147+
148+
StructSliceWithEmptyDefaultElem []Struct `default:"[{}]"`
149+
StructSliceWithFilledDefaultElem []Struct `default:"[{\"WithDefault\":\"changed\"}]"`
147150
}
148151

149152
type Struct struct {
@@ -680,6 +683,15 @@ func TestInit(t *testing.T) {
680683
t.Errorf("it should not initialize a struct with default values")
681684
}
682685
})
686+
687+
t.Run("slice of structs", func(t *testing.T) {
688+
if !reflect.DeepEqual(sample.StructSliceWithEmptyDefaultElem, []Struct{{Embedded: Embedded{Int: 1}, Foo: 0, Bar: 456, WithDefault: "foo"}}) {
689+
t.Errorf("it should automatically fill a slice of structs with elements from default")
690+
}
691+
if !reflect.DeepEqual(sample.StructSliceWithFilledDefaultElem, []Struct{{Embedded: Embedded{Int: 1}, Foo: 0, Bar: 456, WithDefault: "changed"}}) {
692+
t.Errorf("it should overwrite child's default with parent's")
693+
}
694+
})
683695
}
684696

685697
func TestCanUpdate(t *testing.T) {

0 commit comments

Comments
 (0)