diff --git a/copier.go b/copier.go index 3249662..2b6ac5a 100644 --- a/copier.go +++ b/copier.go @@ -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 { diff --git a/copier_test.go b/copier_test.go index 418302a..c46b253 100644 --- a/copier_test.go +++ b/copier_test.go @@ -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