From b369e8a04452531c35a7d5bc9c01db0778aa18e1 Mon Sep 17 00:00:00 2001 From: Josh Hardy Date: Thu, 9 Dec 2021 18:04:15 -0800 Subject: [PATCH] Add test and fix for copy of anonymous field with unexported fields --- copier.go | 4 ++-- copier_test.go | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/copier.go b/copier.go index 6e643be..f1afc36 100644 --- a/copier.go +++ b/copier.go @@ -372,10 +372,10 @@ func deepFields(reflectType reflect.Type) []reflect.StructField { // field name. It is empty for upper case (exported) field names. // See https://golang.org/ref/spec#Uniqueness_of_identifiers if v.PkgPath == "" { + fields = append(fields, v) if v.Anonymous { + // also consider fields of anonymous fields as fields of the root fields = append(fields, deepFields(v.Type)...) - } else { - fields = append(fields, v) } } } diff --git a/copier_test.go b/copier_test.go index bdf6ccb..2799c85 100644 --- a/copier_test.go +++ b/copier_test.go @@ -1453,3 +1453,20 @@ func TestDeepCopySimpleTime(t *testing.T) { t.Errorf("to (%v) value should equal from (%v) value", to, from) } } + +type TimeWrapper struct{ + time.Time +} + +func TestDeepCopyAnonymousFieldTime(t *testing.T) { + from := TimeWrapper{time.Now()} + to := TimeWrapper{} + + err := copier.CopyWithOption(&to, from, copier.Option{DeepCopy: true}) + if err != nil { + t.Error("should not error") + } + if !from.Time.Equal(to.Time) { + t.Errorf("to (%v) value should equal from (%v) value", to.Time, from.Time) + } +}