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 c085d66
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
43 changes: 43 additions & 0 deletions issue90_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
7 changes: 6 additions & 1 deletion merge.go
Original file line number Diff line number Diff line change
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 c085d66

Please sign in to comment.