Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fix copying nil slice #216

Merged
merged 1 commit into from
Jul 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading