From b926fd07ab2f1a37d0015789f24c61c06a9ef499 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 | 42 ++++++++++++++++++++++++++++++++++++++++++ merge.go | 7 ++++++- 2 files changed, 48 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..033a2ac --- /dev/null +++ b/issue90_test.go @@ -0,0 +1,42 @@ +package mergo + +import ( + "reflect" + "testing" +) + +type structWithMap struct { + Data map[string]string +} + + +func TestIssue90(t *testing.T) { + dst := map[string]structWithMap{ + "struct": { + Data: nil, + }, + } + src := map[string]structWithMap{ + "struct": { + Data: map[string]string{ + "foo": "bar", + }, + }, + } + expected := map[string]structWithMap{ + "struct": { + Data: map[string]string{ + "foo": "bar", + }, + }, + } + + err := Merge(&dst, src, 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 {