From cdeab1a0db29fa02acf7f8d01d70024869051100 Mon Sep 17 00:00:00 2001 From: Felix Sun Date: Sat, 11 Sep 2021 14:48:51 +0800 Subject: [PATCH] Be able to set nil --- example_test.go | 2 +- go.mod | 3 +++ map_slice_test.go | 57 +++++++++++++++++++++++++++++++++++++++++++++++ set.go | 6 +++++ 4 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 go.mod diff --git a/example_test.go b/example_test.go index 138f82f..6ddab35 100644 --- a/example_test.go +++ b/example_test.go @@ -303,7 +303,7 @@ func ExampleSet_7notexists() { fmt.Println(err) //Output: - // no such field. + // no such field } diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..ff3743d --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/sunfmin/reflectutils + +go 1.17 diff --git a/map_slice_test.go b/map_slice_test.go index 5628368..ee4619a 100644 --- a/map_slice_test.go +++ b/map_slice_test.go @@ -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") + } + +} \ No newline at end of file diff --git a/set.go b/set.go index 5f14240..f994bf5 100644 --- a/set.go +++ b/set.go @@ -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()