Skip to content

Commit

Permalink
Merge pull request #164 from hhh111119/fix_empty_slice_to_nil
Browse files Browse the repository at this point in the history
fix empty slice is converted to nil in un ConvertibleTo case
  • Loading branch information
jinzhu authored Sep 16, 2022
2 parents 993be5b + 6b861a8 commit 0e264e9
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 12 deletions.
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")
}
}

0 comments on commit 0e264e9

Please sign in to comment.