Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use src map if dst is nil and can't be set #177

Merged
merged 1 commit into from Mar 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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