diff --git a/set.go b/set.go index 2c91798..6648ead 100644 --- a/set.go +++ b/set.go @@ -14,7 +14,6 @@ reflectutils is for setting your struct value by using string name and path that ## How to install go get github.com/sunfmin/reflectutils - */ package reflectutils @@ -46,10 +45,9 @@ func Set(i interface{}, name string, value interface{}) (err error) { for v.Elem().Kind() == reflect.Ptr { v = v.Elem() - } - - if v.IsNil() { - v.Set(reflect.New(v.Type().Elem())) + if v.IsNil() { + v.Set(reflect.New(v.Type().Elem())) + } } sv := v.Elem() @@ -137,7 +135,6 @@ func Set(i interface{}, name string, value interface{}) (err error) { } newslice = reflect.Append(newslice, arrayElem) } else { - if av.Len() > token.ArrayIndex { newslice = reflect.MakeSlice(av.Type(), 0, 0) diff --git a/struct_test.go b/struct_test.go index aea28c3..2a691f8 100644 --- a/struct_test.go +++ b/struct_test.go @@ -178,7 +178,6 @@ func TestSetNotNil(t *testing.T) { if v.Projects[0].Name != "Sendgrid" { t.Error("value was overwriten.") } - } func TestSetStruct(t *testing.T) { @@ -261,7 +260,7 @@ var getcases = []struct { Name: "Languages.en_US.Name", Value: &Person{ Languages: map[string]Language{ - "en_US": Language{ + "en_US": { Name: "English", }, }, @@ -285,7 +284,6 @@ var getcases = []struct { } func TestGet(t *testing.T) { - for _, c := range getcases { t.Run(c.Name, func(t2 *testing.T) { v, err := Get(c.Value, c.Name) @@ -300,7 +298,7 @@ func TestGet(t *testing.T) { }) } - var p = &Person{ + p := &Person{ Company: &Company{ Name: "The Plant 1", }, @@ -321,3 +319,45 @@ func TestGetNil(t *testing.T) { t.Error("Get field nil should be nil") } } + +func TestSetNilToMultiLevelPointer(t *testing.T) { + { + var v *Person + err := Set(&v, "Name", "Felix") + if err != nil { + t.Error(err) + } + if v == nil { + t.Error("v should not be nil") + } + if v.Name != "Felix" { + t.Error("v.Name should be Felix") + } + } + { + var v **Person + err := Set(&v, "Name", "Felix") + if err != nil { + t.Error(err) + } + if v == nil { + t.Error("v should not be nil") + } + if (*v).Name != "Felix" { + t.Error("v.Name should be Felix") + } + } + { + var v ***Person + err := Set(&v, "Name", "Felix") + if err != nil { + t.Error(err) + } + if v == nil { + t.Error("v should not be nil") + } + if (**v).Name != "Felix" { + t.Error("v.Name should be Felix") + } + } +}