Skip to content

Commit

Permalink
Merge pull request #2 from molon/support-ptr-ptr
Browse files Browse the repository at this point in the history
  • Loading branch information
sunfmin authored Jul 23, 2024
2 parents 0891520 + af870bd commit ac287ac
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 10 deletions.
9 changes: 3 additions & 6 deletions set.go
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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)

Expand Down
48 changes: 44 additions & 4 deletions struct_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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",
},
},
Expand All @@ -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)
Expand All @@ -300,7 +298,7 @@ func TestGet(t *testing.T) {
})
}

var p = &Person{
p := &Person{
Company: &Company{
Name: "The Plant 1",
},
Expand All @@ -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")
}
}
}

0 comments on commit ac287ac

Please sign in to comment.