Skip to content

Commit

Permalink
fix: fix copying nil slice
Browse files Browse the repository at this point in the history
  • Loading branch information
helloqiu committed Jul 10, 2024
1 parent 60a1fd2 commit 371cdc1
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
4 changes: 4 additions & 0 deletions copier.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
12 changes: 12 additions & 0 deletions copier_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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'}}
Expand Down

0 comments on commit 371cdc1

Please sign in to comment.