Skip to content

Commit

Permalink
Fix copy slice, close #75
Browse files Browse the repository at this point in the history
  • Loading branch information
jinzhu committed Mar 9, 2021
1 parent 0439967 commit c4beccc
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
5 changes: 5 additions & 0 deletions copier.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,12 @@ func copier(toValue interface{}, fromValue interface{}, opt Option) (err error)
slice := reflect.MakeSlice(reflect.SliceOf(to.Type().Elem()), from.Len(), from.Cap())
to.Set(slice)
}

for i := 0; i < from.Len(); i++ {
if to.Len() < i+1 {
to = reflect.Append(to, reflect.New(to.Type().Elem()).Elem())
}

if !set(to.Index(i), from.Index(i), opt.DeepCopy) {
err = CopyWithOption(to.Index(i).Addr().Interface(), from.Index(i).Interface(), opt)
if err != nil {
Expand Down
23 changes: 23 additions & 0 deletions copier_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,29 @@ func TestCopyFromSliceToSlice2(t *testing.T) {
}
}

type CollectionAlias struct {
CollectionName string `json:"collection_name"`
Name string `json:"name"`
}

func createNewCollectionAlias(collectionName string, name string) *CollectionAlias {
return &CollectionAlias{
CollectionName: collectionName,
Name: name,
}
}

func TestCopyFromSliceToSlice3(t *testing.T) {
expectedResult := []*CollectionAlias{
createNewCollectionAlias("collection", "collection_alias1"),
createNewCollectionAlias("collection", "collection_alias2"),
createNewCollectionAlias("collection", "collection_alias3"),
}

mockedResult := []*CollectionAlias{}
copier.Copy(&mockedResult, &expectedResult)
}

func TestEmbeddedAndBase(t *testing.T) {
type Base struct {
BaseField1 int
Expand Down

0 comments on commit c4beccc

Please sign in to comment.