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
12 changes: 11 additions & 1 deletion copier.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ func copier(toValue interface{}, fromValue interface{}, opt Option) (err error)
isSlice bool
amount = 1
from = indirect(reflect.ValueOf(fromValue))
to = indirect(reflect.ValueOf(toValue))
to = indirectAndFill(reflect.ValueOf(toValue))
converters = opt.converters()
mappings = opt.fieldNameMapping()
)
Expand Down Expand Up @@ -544,6 +544,16 @@ func deepFields(reflectType reflect.Type) []reflect.StructField {
return res
}

func indirectAndFill(reflectValue reflect.Value) reflect.Value {
for reflectValue.Kind() == reflect.Ptr {
if reflectValue.IsNil() {
reflectValue.Set(reflect.New(reflectValue.Type().Elem()))
}
reflectValue = reflectValue.Elem()
}
return reflectValue
}

func indirect(reflectValue reflect.Value) reflect.Value {
for reflectValue.Kind() == reflect.Ptr {
reflectValue = reflectValue.Elem()
Expand Down
18 changes: 18 additions & 0 deletions copier_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1762,3 +1762,21 @@ func TestNestedNilPointerStruct(t *testing.T) {
t.Errorf("to (%v) value should equal from (%v) value", to.Title, from.Title)
}
}

func TestCopyToNilPointerOfStruct(t *testing.T) {
type struct1 struct {
A int
}
type struct2 struct {
A int
}
s1 := struct1{A: 1}
var s2 *struct2
err := copier.Copy(&s2, s1)
if err != nil {
t.Error("should not error")
}
if s1.A != (*s2).A {
t.Error("should equal")
}
}