Skip to content

Commit

Permalink
Fix copy slice, close #88
Browse files Browse the repository at this point in the history
  • Loading branch information
jinzhu committed Mar 9, 2021
1 parent c4beccc commit 54959a4
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 18 deletions.
2 changes: 1 addition & 1 deletion copier.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ func copier(toValue interface{}, fromValue interface{}, opt Option) (err error)

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

if !set(to.Index(i), from.Index(i), opt.DeepCopy) {
Expand Down
3 changes: 0 additions & 3 deletions copier_issue84_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package copier_test

import (
"fmt"
"testing"
"time"

Expand Down Expand Up @@ -81,9 +80,7 @@ func TestIssue84(t *testing.T) {
destObj2 := NotWork{}

copier.CopyWithOption(&destObj1, &workObj, copier.Option{IgnoreEmpty: true, DeepCopy: false})
fmt.Println(destObj1)

copier.CopyWithOption(&destObj2, &notWorkObj, copier.Option{IgnoreEmpty: true, DeepCopy: false})
fmt.Println(destObj2)
})
}
31 changes: 17 additions & 14 deletions copier_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -243,27 +243,30 @@ 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) {
type CollectionAlias struct {
CollectionName string `json:"collection_name"`
Name string `json:"name"`
}
}

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

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

if len(mockedResult) != len(expectedResult) {
t.Fatalf("failed to copy results")
}

for idx := range mockedResult {
if mockedResult[idx].Name != mockedResult[idx].Name || mockedResult[idx].CollectionName != mockedResult[idx].CollectionName {
t.Fatalf("failed to copy results")
}
}
}

func TestEmbeddedAndBase(t *testing.T) {
Expand Down

0 comments on commit 54959a4

Please sign in to comment.