Skip to content

Commit

Permalink
Fixed panic with nested pointer structs
Browse files Browse the repository at this point in the history
  • Loading branch information
NicklasWallgren committed Jan 10, 2023
1 parent 71be026 commit 7985840
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
12 changes: 11 additions & 1 deletion copier.go
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ func copier(toValue interface{}, fromValue interface{}, opt Option) (err error)
}

srcFieldName, destFieldName := getFieldName(name, flgs)
if fromField := source.FieldByName(srcFieldName); fromField.IsValid() && !shouldIgnore(fromField, opt.IgnoreEmpty) {
if fromField := fieldByNameOrZeroValue(source, srcFieldName); fromField.IsValid() && !shouldIgnore(fromField, opt.IgnoreEmpty) {
// process for nested anonymous field
destFieldNotSet := false
if f, ok := dest.Type().FieldByName(destFieldName); ok {
Expand Down Expand Up @@ -400,6 +400,16 @@ func copier(toValue interface{}, fromValue interface{}, opt Option) (err error)
return
}

func fieldByNameOrZeroValue(source reflect.Value, fieldName string) (value reflect.Value) {
defer func() {
if err := recover(); err != nil {
value = reflect.Value{}
}
}()

return source.FieldByName(fieldName)
}

func copyUnexportedStructFields(to, from reflect.Value) {
if from.Kind() != reflect.Struct || to.Kind() != reflect.Struct || !from.Type().AssignableTo(to.Type()) {
return
Expand Down
30 changes: 30 additions & 0 deletions copier_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1732,3 +1732,33 @@ func TestEmptySlice(t *testing.T) {
t.Error("from should be empty slice nil")
}
}

func TestNestedNilPointerStruct(t *testing.T) {
type destination struct {
Title string
}

type NestedSource struct {
ID int
}

type source struct {
Title string
*NestedSource
}

from := &source{
Title: "A title to be copied",
}

to := destination{}

err := copier.Copy(&to, from)
if err != nil {
t.Error("should not error")
}

if from.Title != to.Title {
t.Errorf("to (%v) value should equal from (%v) value", to.Title, from.Title)
}
}

0 comments on commit 7985840

Please sign in to comment.