From 54959a4959ebeba02a164b09af052fcbe621f445 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Tue, 9 Mar 2021 18:05:47 +0800 Subject: [PATCH] Fix copy slice, close #88 --- copier.go | 2 +- copier_issue84_test.go | 3 --- copier_test.go | 31 +++++++++++++++++-------------- 3 files changed, 18 insertions(+), 18 deletions(-) diff --git a/copier.go b/copier.go index 2b6ac5a..9117322 100644 --- a/copier.go +++ b/copier.go @@ -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) { diff --git a/copier_issue84_test.go b/copier_issue84_test.go index 2549aaf..54b1944 100644 --- a/copier_issue84_test.go +++ b/copier_issue84_test.go @@ -1,7 +1,6 @@ package copier_test import ( - "fmt" "testing" "time" @@ -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, ¬WorkObj, copier.Option{IgnoreEmpty: true, DeepCopy: false}) - fmt.Println(destObj2) }) } diff --git a/copier_test.go b/copier_test.go index c46b253..4df34c5 100644 --- a/copier_test.go +++ b/copier_test.go @@ -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) {