Skip to content

Commit

Permalink
Be able to set nil
Browse files Browse the repository at this point in the history
  • Loading branch information
sunfmin committed Sep 11, 2021
1 parent f129c4f commit cdeab1a
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 1 deletion.
2 changes: 1 addition & 1 deletion example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ func ExampleSet_7notexists() {

fmt.Println(err)
//Output:
// no such field.
// no such field
}


Expand Down
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/sunfmin/reflectutils

go 1.17
57 changes: 57 additions & 0 deletions map_slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,60 @@ func TestSlices(t *testing.T) {
}

}

func TestMapSetNil(t *testing.T) {
m := make(map[string]int)
Set(&m, "", nil)
if m != nil {
t.Errorf("got non-nil (%p), want nil", m)
}
}

func TestSliceSetNil(t *testing.T) {
m := []int{1}
err := Set(&m, "", nil)
if err != nil {
panic(err)
}
if m != nil {
t.Errorf("got non-nil (%p), want nil", m)
}

}

func TestStructSetNil(t *testing.T) {
type S struct {
Val string
}
m := &S{Val: "123"}
err := Set(&m, "", nil)
if err != nil {
panic(err)
}


if m != nil {
t.Errorf("got non-nil (%#+v), want nil", m)
}
}

func TestSetFieldNil(t *testing.T) {

type S struct {
Value []int
}

var s = &S{
Value: []int{1, 2},
}

err := Set(s, "Value", nil)
if err != nil {
panic(err)
}

if s.Value != nil {
panic("s.Value is not nil")
}

}
6 changes: 6 additions & 0 deletions set.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ func Set(i interface{}, name string, value interface{}) (err error) {
return
}
default:
if value == nil {
vm := reflect.ValueOf(i)
vm.Elem().Set(reflect.Zero(vm.Elem().Type()))
return
}

valv := reflect.ValueOf(value)
for valv.Kind() == reflect.Ptr {
valv = valv.Elem()
Expand Down

0 comments on commit cdeab1a

Please sign in to comment.