From c085d66e6b45f4f226a313bdddfbcbfb8cbbf8f0 Mon Sep 17 00:00:00 2001 From: Nicolas De Loof Date: Thu, 18 Feb 2021 13:23:28 +0100 Subject: [PATCH] use src map if dst is nil and can't be set see https://github.com/imdario/mergo/issues/90 Signed-off-by: Nicolas De Loof --- issue90_test.go | 43 +++++++++++++++++++++++++++++++++++++++++++ merge.go | 7 ++++++- 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 issue90_test.go diff --git a/issue90_test.go b/issue90_test.go new file mode 100644 index 0000000..872a327 --- /dev/null +++ b/issue90_test.go @@ -0,0 +1,43 @@ +package mergo_test + +import ( + "github.com/imdario/mergo" + "reflect" + "testing" +) + +type structWithStringMap struct { + Data map[string]string +} + + +func TestIssue90(t *testing.T) { + dst := map[string]structWithStringMap{ + "struct": { + Data: nil, + }, + } + src := map[string]structWithStringMap{ + "struct": { + Data: map[string]string{ + "foo": "bar", + }, + }, + } + expected := map[string]structWithStringMap{ + "struct": { + Data: map[string]string{ + "foo": "bar", + }, + }, + } + + err := mergo.Merge(&dst, src, mergo.WithOverride) + if err != nil { + t.Errorf("unexpected error %v", err) + } + + if !reflect.DeepEqual(dst, expected) { + t.Errorf("expected: %#v\ngot: %#v", expected, dst) + } +} diff --git a/merge.go b/merge.go index afa84a1..740bae0 100644 --- a/merge.go +++ b/merge.go @@ -101,7 +101,12 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co } case reflect.Map: if dst.IsNil() && !src.IsNil() { - dst.Set(reflect.MakeMap(dst.Type())) + if dst.CanSet() { + dst.Set(reflect.MakeMap(dst.Type())) + } else { + dst = src + return + } } if src.Kind() != reflect.Map {