Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: error when trying initialize slice of structs with default tag #46

Merged
merged 1 commit into from
Aug 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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