Skip to content

Commit cdeab1a

Browse files
committed
Be able to set nil
1 parent f129c4f commit cdeab1a

4 files changed

Lines changed: 67 additions & 1 deletion

File tree

example_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -303,7 +303,7 @@ func ExampleSet_7notexists() {
303303

304304
fmt.Println(err)
305305
//Output:
306-
// no such field.
306+
// no such field
307307
}
308308

309309

go.mod

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module github.com/sunfmin/reflectutils
2+
3+
go 1.17

map_slice_test.go

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,3 +71,60 @@ func TestSlices(t *testing.T) {
7171
}
7272

7373
}
74+
75+
func TestMapSetNil(t *testing.T) {
76+
m := make(map[string]int)
77+
Set(&m, "", nil)
78+
if m != nil {
79+
t.Errorf("got non-nil (%p), want nil", m)
80+
}
81+
}
82+
83+
func TestSliceSetNil(t *testing.T) {
84+
m := []int{1}
85+
err := Set(&m, "", nil)
86+
if err != nil {
87+
panic(err)
88+
}
89+
if m != nil {
90+
t.Errorf("got non-nil (%p), want nil", m)
91+
}
92+
93+
}
94+
95+
func TestStructSetNil(t *testing.T) {
96+
type S struct {
97+
Val string
98+
}
99+
m := &S{Val: "123"}
100+
err := Set(&m, "", nil)
101+
if err != nil {
102+
panic(err)
103+
}
104+
105+
106+
if m != nil {
107+
t.Errorf("got non-nil (%#+v), want nil", m)
108+
}
109+
}
110+
111+
func TestSetFieldNil(t *testing.T) {
112+
113+
type S struct {
114+
Value []int
115+
}
116+
117+
var s = &S{
118+
Value: []int{1, 2},
119+
}
120+
121+
err := Set(s, "Value", nil)
122+
if err != nil {
123+
panic(err)
124+
}
125+
126+
if s.Value != nil {
127+
panic("s.Value is not nil")
128+
}
129+
130+
}

set.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,12 @@ func Set(i interface{}, name string, value interface{}) (err error) {
6363
return
6464
}
6565
default:
66+
if value == nil {
67+
vm := reflect.ValueOf(i)
68+
vm.Elem().Set(reflect.Zero(vm.Elem().Type()))
69+
return
70+
}
71+
6672
valv := reflect.ValueOf(value)
6773
for valv.Kind() == reflect.Ptr {
6874
valv = valv.Elem()

0 commit comments

Comments
 (0)