diff --git a/copier.go b/copier.go index 3e78f24..e118ebb 100644 --- a/copier.go +++ b/copier.go @@ -227,7 +227,7 @@ 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) } - if fromType.ConvertibleTo(toType) { + if opt.DeepCopy || fromType.ConvertibleTo(toType) { for i := 0; i < from.Len(); i++ { if to.Len() < i+1 { to.Set(reflect.Append(to, reflect.New(to.Type().Elem()).Elem())) diff --git a/copier_different_type_test.go b/copier_different_type_test.go index aaac92d..7eecf15 100644 --- a/copier_different_type_test.go +++ b/copier_different_type_test.go @@ -2,6 +2,7 @@ package copier_test import ( "database/sql" + "reflect" "testing" "time" @@ -220,3 +221,46 @@ func TestCopyFromBaseToSqlNullWithOptionDeepCopy(t *testing.T) { t.Errorf("b.H = %v, want %v", b.H, "deep") } } + +func TestCopyWithAnySlice(t *testing.T) { + t.Run("AnySliceWithDeepCopy", func(t *testing.T) { + from := []interface{}{ + map[string]interface{}{ + "K1": "V1", + "K2": "V2", + }, + } + var to []map[string]string + err := copier.CopyWithOption(&to, from, copier.Option{DeepCopy: true}) + if err != nil { + t.Errorf("CopyStructWithOption() error = %v", err) + return + } + want := []map[string]string{{"K1": "V1", "K2": "V2"}} + ok := reflect.DeepEqual(to, want) + if !ok { + t.Errorf("toVal = %v, want %v", to, want) + } + }) + t.Run("AnySliceWithoutDeepCopy", func(t *testing.T) { + from := []interface{}{ + map[string]interface{}{ + "K1": "V1", + "K2": "V2", + }, + } + var to []map[string]string + err := copier.CopyWithOption(&to, from, copier.Option{DeepCopy: false}) + if err != nil { + t.Errorf("CopyStructWithOption() error = %v", err) + return + } + want := []map[string]string{ + nil, + } + ok := reflect.DeepEqual(to, want) + if !ok { + t.Errorf("toVal = %v, want %v", to, want) + } + }) +}