diff --git a/issue187_test.go b/issue187_test.go new file mode 100644 index 0000000..49aabfc --- /dev/null +++ b/issue187_test.go @@ -0,0 +1,71 @@ +package mergo_test + +import ( + "dario.cat/mergo" + "testing" +) + +func TestIssue187MergeStructToMap(t *testing.T) { + dst := map[string]interface{}{ + "empty": "data", + } + + src := struct { + Foo string + Bar int + Empty string + }{ + Foo: "hello", + Bar: 42, + } + if err := mergo.Map(&dst, src); err != nil { + t.Error(err) + } + if dst["foo"] != "hello" || dst["bar"] != 42 || dst["empty"] != "data" { + t.Errorf("expected dst to be {foo: hello, bar: 42, empty: data}, got {foo: %v, bar: %v, empty: %v}", dst["foo"], dst["bar"], dst["empty"]) + } +} + +func TestIssue187MergeStructToMapWithOverwrite(t *testing.T) { + dst := map[string]interface{}{ + "foo": "initial", + "bar": 1, + "empty": "data", + } + src := struct { + Foo string + Bar int + Empty string + }{ + Foo: "hello", + Bar: 42, + } + if err := mergo.Map(&dst, src, mergo.WithOverride); err != nil { + t.Error(err) + } + if dst["foo"] != "hello" || dst["bar"] != 42 || dst["empty"] != "data" { + t.Errorf("expected dst to be {foo: hello, bar: 42, empty: data}, got {foo: %v, bar: %v, empty: %v}", dst["foo"], dst["bar"], dst["empty"]) + } +} + +func TestIssue187MergeStructToMapWithOverwriteWithEmptyValue(t *testing.T) { + dst := map[string]interface{}{ + "foo": "initial", + "bar": 1, + "empty": "data", + } + src := struct { + Foo string + Bar int + Empty string + }{ + Foo: "hello", + Bar: 42, + } + if err := mergo.Map(&dst, src, mergo.WithOverwriteWithEmptyValue); err != nil { + t.Error(err) + } + if dst["foo"] != "hello" || dst["bar"] != 42 || dst["empty"] != "" { + t.Errorf("expected dst to be {foo: hello, bar: 42, empty: }, got {foo: %v, bar: %v, empty: %v}", dst["foo"], dst["bar"], dst["empty"]) + } +} diff --git a/map.go b/map.go index 95ccd12..759b4f7 100644 --- a/map.go +++ b/map.go @@ -58,7 +58,7 @@ func deepMap(dst, src reflect.Value, visited map[uintptr]*visit, depth int, conf } fieldName := field.Name fieldName = changeInitialCase(fieldName, unicode.ToLower) - if _, ok := dstMap[fieldName]; !ok || (!isEmptyValue(reflect.ValueOf(src.Field(i).Interface()), !config.ShouldNotDereference) && overwrite) { + if _, ok := dstMap[fieldName]; !ok || (!isEmptyValue(reflect.ValueOf(src.Field(i).Interface()), !config.ShouldNotDereference) && overwrite) || config.overwriteWithEmptyValue { dstMap[fieldName] = src.Field(i).Interface() } }