From 371cdc1e5ea85522316d52bb74c14346aae9cb37 Mon Sep 17 00:00:00 2001 From: helloqiu Date: Wed, 10 Jul 2024 17:36:39 +0800 Subject: [PATCH] fix: fix copying nil slice --- copier.go | 4 ++++ copier_test.go | 12 ++++++++++++ 2 files changed, 16 insertions(+) diff --git a/copier.go b/copier.go index 0cc6465..5b07ac1 100644 --- a/copier.go +++ b/copier.go @@ -211,6 +211,10 @@ func copier(toValue interface{}, fromValue interface{}, opt Option) (err error) } if from.Kind() == reflect.Slice && to.Kind() == reflect.Slice { + // Return directly if both slices are nil + if from.IsNil() && to.IsNil() { + return + } if to.IsNil() { slice := reflect.MakeSlice(reflect.SliceOf(to.Type().Elem()), from.Len(), from.Cap()) to.Set(slice) diff --git a/copier_test.go b/copier_test.go index 4769eba..1441df5 100644 --- a/copier_test.go +++ b/copier_test.go @@ -112,6 +112,18 @@ func checkEmployee2(employee Employee, user *User, t *testing.T, testCase string checkEmployee(employee, *user, t, testCase) } +func TestCopySliceOfDifferentTypes(t *testing.T) { + var ss []string + var is []int + if err := copier.Copy(&ss, is); err != nil { + t.Error(err) + } + var anotherSs []string + if !reflect.DeepEqual(ss, anotherSs) { + t.Errorf("Copy nil slice to nil slice should get nil slice") + } +} + func TestCopyStruct(t *testing.T) { var fakeAge int32 = 12 user := User{Name: "Jinzhu", Nickname: "jinzhu", Age: 18, FakeAge: &fakeAge, Role: "Admin", Notes: []string{"hello world", "welcome"}, flags: []byte{'x'}}