Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix empty slice is converted to nil in un ConvertibleTo case #164

Merged
merged 2 commits into from
Sep 16, 2022
Merged
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
25 changes: 13 additions & 12 deletions copier.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,26 +176,27 @@ func copier(toValue interface{}, fromValue interface{}, opt Option) (err error)
return
}

if from.Kind() == reflect.Slice && to.Kind() == reflect.Slice && fromType.ConvertibleTo(toType) {
if from.Kind() == reflect.Slice && to.Kind() == reflect.Slice {
if to.IsNil() {
slice := reflect.MakeSlice(reflect.SliceOf(to.Type().Elem()), from.Len(), from.Cap())
to.Set(slice)
}
if 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()))
}

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

if !set(to.Index(i), from.Index(i), opt.DeepCopy, converters) {
// ignore error while copy slice element
err = copier(to.Index(i).Addr().Interface(), from.Index(i).Interface(), opt)
if err != nil {
continue
if !set(to.Index(i), from.Index(i), opt.DeepCopy, converters) {
// ignore error while copy slice element
err = copier(to.Index(i).Addr().Interface(), from.Index(i).Interface(), opt)
if err != nil {
continue
}
}
}
return
}
return
}

if fromType.Kind() != reflect.Struct || toType.Kind() != reflect.Struct {
Expand Down
30 changes: 30 additions & 0 deletions copier_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1666,3 +1666,33 @@ func TestSqlNullFiled(t *testing.T) {
t.Errorf("to (%v) value should equal from (%v) value", to.MkExpiryDateType, from.MkExpiryDateType.Int32)
}
}

func TestEmptySlice(t *testing.T) {
type Str1 string
type Str2 string
type Input1 struct {
Val Str1
}
type Input2 struct {
Val Str2
}
to := []*Input1(nil)
from := []*Input2{}
err := copier.Copy(&to, &from)
if err != nil {
t.Error("should not error")
}
if from == nil {
t.Error("from should be empty slice not nil")
}

to = []*Input1(nil)
from = []*Input2(nil)
err = copier.Copy(&to, &from)
if err != nil {
t.Error("should not error")
}
if from != nil {
t.Error("from should be empty slice nil")
}
}