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

Copy to nil empty interface #217

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
6 changes: 6 additions & 0 deletions copier.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,12 @@ func copier(toValue interface{}, fromValue interface{}, opt Option) (err error)
return ErrInvalidCopyFrom
}

// If the target is an empty interface with value nil, simply copy the value
if from.Kind() == reflect.Struct && from.Type().AssignableTo(to.Type()) && reflect.TypeOf(to.Interface()) == nil {
to.Set(from)
return
}

fromType, isPtrFrom := indirectType(from.Type())
toType, _ := indirectType(to.Type())

Expand Down
32 changes: 32 additions & 0 deletions copier_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1774,3 +1774,35 @@ func TestNestedNilPointerStruct(t *testing.T) {
t.Errorf("to (%v) value should equal from (%v) value", to.Title, from.Title)
}
}

type testStruct struct {
Prop string
}

type testHolder struct {
Data interface{}
}

func newHolder(data interface{}) testHolder {
h := testHolder{}
copier.Copy(&(h.Data), data)
return h
}

func getDataFromHolder(holder testHolder, data interface{}) {
copier.Copy(data, holder.Data)
}

func TestCopyToNilEmptyInterface(t *testing.T) {
expected := testStruct{Prop: "expected"}

holder := newHolder(&expected)

actual := testStruct{}

getDataFromHolder(holder, &actual)

if expected.Prop != actual.Prop {
t.Fatalf("wanted %s got %s", expected.Prop, actual.Prop)
}
}