Skip to content

Commit

Permalink
👔 update: struts - InitDefaults() support init non-zero ptr sub-struc…
Browse files Browse the repository at this point in the history
…t field
  • Loading branch information
inhere committed Jun 5, 2023
1 parent af89719 commit 0c460d4
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
9 changes: 9 additions & 0 deletions structs/init.go
Expand Up @@ -93,6 +93,15 @@ func initDefaults(rv reflect.Value, opt *InitOptions) error {

// skip on field has value
if !fv.IsZero() {
// special: handle for pointer struct field
if fv.Kind() == reflect.Pointer {
fv = fv.Elem()
if fv.Kind() == reflect.Struct {
if err := initDefaults(fv, opt); err != nil {
return err
}
}
}
continue
}

Expand Down
12 changes: 10 additions & 2 deletions structs/init_test.go
Expand Up @@ -120,9 +120,10 @@ func TestInitDefaults_nestStruct(t *testing.T) {

u = &User{Extra: ExtraDefault{Github: "some url"}}
err = structs.InitDefaults(u)
dump.P(u)
// dump.P(u)
assert.NoErr(t, err)
assert.Eq(t, "chengdu", u.Extra.City)
assert.Eq(t, "some url", u.Extra.Github)
}

func TestInitDefaults_ptrStructField(t *testing.T) {
Expand All @@ -141,6 +142,13 @@ func TestInitDefaults_ptrStructField(t *testing.T) {
assert.Eq(t, 30, u.Age)
assert.Eq(t, "chengdu", u.Extra.City)
assert.Eq(t, "https://github.com/inhere", u.Extra.Github)

u = &User{Extra: &ExtraDefault{Github: "some url"}}
err = structs.InitDefaults(u)
// dump.P(u)
assert.NoErr(t, err)
assert.Eq(t, "chengdu", u.Extra.City)
assert.Eq(t, "some url", u.Extra.Github)
}

func TestInitDefaults_sliceField(t *testing.T) {
Expand All @@ -161,7 +169,7 @@ func TestInitDefaults_sliceField(t *testing.T) {
assert.Eq(t, []int64{34, 456}, u.TagIds)
}

func TestInitDefaults_InitStructSlice(t *testing.T) {
func TestInitDefaults_initStructSlice(t *testing.T) {
// test for slice struct field
type User struct {
Name string `default:"inhere"`
Expand Down

0 comments on commit 0c460d4

Please sign in to comment.