Skip to content

Commit

Permalink
use src map if dst is nil and can't be set
Browse files Browse the repository at this point in the history
see #90

Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
  • Loading branch information
ndeloof committed Feb 18, 2021
1 parent cd55aea commit b926fd0
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
42 changes: 42 additions & 0 deletions 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)
}
}
7 changes: 6 additions & 1 deletion merge.go
Expand Up @@ -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 {
Expand Down

0 comments on commit b926fd0

Please sign in to comment.