Skip to content

Commit

Permalink
Merge pull request #46 from orangejohny/master
Browse files Browse the repository at this point in the history
fix: error when trying initialize slice of structs with `default` tag
  • Loading branch information
creasty authored Aug 13, 2024
2 parents 5220e08 + 586c267 commit abebf4b
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
2 changes: 1 addition & 1 deletion defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
Expand Down
12 changes: 12 additions & 0 deletions defaults_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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) {
Expand Down

0 comments on commit abebf4b

Please sign in to comment.