Skip to content

Commit

Permalink
Merge pull request #253 from vsemichev/master
Browse files Browse the repository at this point in the history
fixes issue #187
  • Loading branch information
darccio authored Aug 17, 2024
2 parents cde9f0e + 2f1a615 commit 96f24af
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 1 deletion.
71 changes: 71 additions & 0 deletions issue187_test.go
Original file line number Diff line number Diff line change
@@ -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"])
}
}
2 changes: 1 addition & 1 deletion map.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 v, ok := dstMap[fieldName]; !ok || (isEmptyValue(reflect.ValueOf(v), !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()
}
}
Expand Down

0 comments on commit 96f24af

Please sign in to comment.