Skip to content

Commit

Permalink
👔 up: structs - update InitDefaults() support init for not empty stru…
Browse files Browse the repository at this point in the history
…ct-slice field
  • Loading branch information
inhere committed Jun 16, 2023
1 parent d0b5185 commit ce42976
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
15 changes: 15 additions & 0 deletions structs/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,21 @@ func initDefaults(rv reflect.Value, opt *InitOptions) error {
return err
}
}
} else if fv.Kind() == reflect.Slice {
el := sf.Type.Elem()
if el.Kind() == reflect.Pointer {
el = el.Elem()
}

// init sub struct in slice. like `[]SubStruct` or `[]*SubStruct`
if el.Kind() == reflect.Struct && fv.Len() > 0 {
for i := 0; i < fv.Len(); i++ {
subFv := reflect.Indirect(fv.Index(i))
if err := initDefaults(subFv, opt); err != nil {
return err
}
}
}
}
continue
}
Expand Down
23 changes: 22 additions & 1 deletion structs/init_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,27 @@ func TestInitDefaults(t *testing.T) {
assert.Eq(t, "", u1.city)
// dump.P(u1)
// fmt.Printf("%+v\n", u1)
}

err = structs.InitDefaults([]string{"invalid"})
func TestInitDefaults_error(t *testing.T) {
err := structs.InitDefaults([]string{"invalid"})
assert.ErrMsg(t, err, "must be provider an pointer value")

arr := []string{"invalid"}
err = structs.InitDefaults(&arr)
assert.ErrMsg(t, err, "must be provider an struct value")

type User struct {
Name string `default:"inhere"`
Age int `default:"abc"`
}

u := &User{}
err = structs.InitDefaults(u)
assert.ErrMsg(t, err, comdef.ErrConvType.Error())
assert.Eq(t, "inhere", u.Name)
assert.Eq(t, 0, u.Age)
// dump.P(u)
}

func TestInitDefaults_parseEnv(t *testing.T) {
Expand Down Expand Up @@ -197,6 +211,13 @@ func TestInitDefaults_initStructSlice(t *testing.T) {
assert.NoErr(t, err)
assert.NotEmpty(t, u1.Extra)
assert.Eq(t, "chengdu", u1.Extra[0].City)

// test for not empty slice struct field
u2 := &User1{Extra: []*ExtraDefault{{City: "sh"}}}
err = structs.Init(u2)
// dump.P(u2)
assert.NoErr(t, err)
assert.Eq(t, "sh", u2.Extra[0].City)
}

func TestInitDefaults_ptrField(t *testing.T) {
Expand Down

0 comments on commit ce42976

Please sign in to comment.