From 415559ef90b6a5f661f536d9dacd329a4a2fdf16 Mon Sep 17 00:00:00 2001 From: Nick Muller Date: Wed, 24 Jun 2020 14:59:08 +0200 Subject: [PATCH] Allow directly mapping of structs that are of the same type. --- automapper.go | 2 +- automapper_test.go | 18 ++++++++++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/automapper.go b/automapper.go index 1ef7f4e..432d8ed 100644 --- a/automapper.go +++ b/automapper.go @@ -58,7 +58,7 @@ func MapLoose(source, dest interface{}) { func mapValues(sourceVal, destVal reflect.Value, loose bool) { destType := destVal.Type() - if destType.Kind() == reflect.Struct { + if destType.Kind() == reflect.Struct && sourceVal.Type() != destVal.Type() { if sourceVal.Type().Kind() == reflect.Ptr { if sourceVal.IsNil() { // If source is nil, it maps to an empty struct diff --git a/automapper_test.go b/automapper_test.go index bd8b93e..17883f4 100644 --- a/automapper_test.go +++ b/automapper_test.go @@ -3,9 +3,9 @@ package automapper import ( - "testing" - "github.com/stretchr/testify/assert" + "testing" + "time" ) func TestPanicWhenDestIsNotPointer(t *testing.T) { @@ -256,6 +256,20 @@ func TestWithLooseOption(t *testing.T) { assert.Equal(t, dest.Bar, 0) } +func TestSetStructOfSameTypeDirectly(t *testing.T) { + type FooType struct { + time.Time + } + source := struct { + Foo FooType + }{FooType{Time: time.Now().UTC()}} + dest := struct { + Foo FooType + }{} + Map(&source, &dest) + assert.Equal(t, source.Foo.String(), dest.Foo.String()) +} + type SourceParent struct { Children []SourceTypeA }