Skip to content

Commit

Permalink
Add slice of ptr support
Browse files Browse the repository at this point in the history
  • Loading branch information
jinzhu committed Jan 15, 2021
1 parent bee69a9 commit d927746
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 7 deletions.
5 changes: 3 additions & 2 deletions copier.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ func copier(toValue interface{}, fromValue interface{}, opt Option) (err error)

if from.Kind() == reflect.Slice && to.Kind() == reflect.Slice && fromType.ConvertibleTo(toType) {
if to.IsNil() {
slice := reflect.MakeSlice(reflect.SliceOf(toType), from.Len(), from.Cap())
slice := reflect.MakeSlice(reflect.SliceOf(to.Type().Elem()), from.Len(), from.Cap())
to.Set(slice)
}
for i := 0; i < from.Len(); i++ {
Expand All @@ -127,7 +127,8 @@ func copier(toValue interface{}, fromValue interface{}, opt Option) (err error)
continue
}
}
to.Index(i).Set(toValue)

set(to.Index(i), toValue, opt.DeepCopy)
}
return
}
Expand Down
5 changes: 4 additions & 1 deletion copier_benchmark_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,10 @@ func BenchmarkNamaCopy(b *testing.B) {
Age: int64(user.Age),
FakeAge: int(*user.FakeAge),
DoubleAge: user.DoubleAge(),
Notes: user.Notes,
}

for _, note := range user.Notes {
employee.Notes = append(employee.Notes, &note)
}
employee.Role(user.Role)
}
Expand Down
14 changes: 10 additions & 4 deletions copier_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package copier_test

import (
"errors"
"reflect"
"testing"
"time"

Expand Down Expand Up @@ -33,7 +32,7 @@ type Employee struct {
EmployeID int64
DoubleAge int32
SuperRule string
Notes []string
Notes []*string
flags []byte
}

Expand Down Expand Up @@ -70,8 +69,15 @@ func checkEmployee(employee Employee, user User, t *testing.T, testCase string)
if employee.SuperRule != "Super "+user.Role {
t.Errorf("%v: Copy to method doesn't work", testCase)
}
if !reflect.DeepEqual(employee.Notes, user.Notes) {
t.Errorf("%v: Copy from slice doesn't work", testCase)

if len(employee.Notes) != len(user.Notes) {
t.Fatalf("%v: Copy from slice doesn't work, employee notes len: %v, user: %v", testCase, len(employee.Notes), len(user.Notes))
}

for idx, note := range user.Notes {
if note != *employee.Notes[idx] {
t.Fatalf("%v: Copy from slice doesn't work, notes idx: %v employee: %v user: %v", testCase, idx, *employee.Notes[idx], note)
}
}
}

Expand Down

0 comments on commit d927746

Please sign in to comment.