From 424f8b2b4b1c45c5ef63cf65dbc78e78764ebc9a Mon Sep 17 00:00:00 2001 From: Zhiyu Wang Date: Wed, 17 Aug 2022 07:48:11 +0000 Subject: [PATCH] Fix: validate before set Signed-off-by: Zhiyu Wang --- issue220_test.go | 33 +++++++++++++++++++++++++++++++++ merge.go | 2 +- 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 issue220_test.go diff --git a/issue220_test.go b/issue220_test.go new file mode 100644 index 0000000..164f5bd --- /dev/null +++ b/issue220_test.go @@ -0,0 +1,33 @@ +package mergo_test + +import ( + "reflect" + "testing" + + "github.com/imdario/mergo" +) + +func TestIssue220(t *testing.T) { + dst := []interface{}{ + map[string]int{ + "a": 1, + }, + } + src := []interface{}{ + "nil", + } + expected := []interface{}{ + map[string]int{ + "a": 1, + }, + } + + err := mergo.Merge(&dst, src, mergo.WithSliceDeepCopy) + 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 4b47d0b..16e55e1 100644 --- a/merge.go +++ b/merge.go @@ -110,7 +110,7 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co } if src.Kind() != reflect.Map { - if overwrite { + if overwrite && dst.CanSet() { dst.Set(src) } return