Skip to content

Commit

Permalink
Merge pull request #177 from ndeloof/master
Browse files Browse the repository at this point in the history
use src map if dst is nil and can't be set
  • Loading branch information
darccio committed Mar 3, 2021
2 parents aa32fec + c085d66 commit b617763
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
@@ -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
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 b617763

Please sign in to comment.