Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion copier.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()))
Expand Down
44 changes: 44 additions & 0 deletions copier_different_type_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package copier_test

import (
"database/sql"
"reflect"
"testing"
"time"

Expand Down Expand Up @@ -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)
}
})
}