Skip to content

Commit

Permalink
Merge pull request #70 from aouyang1/master
Browse files Browse the repository at this point in the history
Override slices if WithOverride is specified
  • Loading branch information
darccio committed Apr 2, 2018
2 parents 9e42abc + e6c5cef commit 1ab68ab
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
38 changes: 38 additions & 0 deletions issue64_test.go
@@ -0,0 +1,38 @@
package mergo

import (
"testing"
)

type Student struct {
Name string
Books []string
}

var testData = []struct {
S1 Student
S2 Student
ExpectedSlice []string
}{
{Student{"Jack", []string{"a", "B"}}, Student{"Tom", []string{"1"}}, []string{"a", "B"}},
{Student{"Jack", []string{"a", "B"}}, Student{"Tom", []string{}}, []string{"a", "B"}},
{Student{"Jack", []string{}}, Student{"Tom", []string{"1"}}, []string{"1"}},
{Student{"Jack", []string{}}, Student{"Tom", []string{}}, []string{}},
}

func TestIssue64MergeSliceWithOverride(t *testing.T) {
for _, data := range testData {
err := Merge(&data.S2, data.S1, WithOverride)
if err != nil {
t.Errorf("Error while merging %s", err)
}
if len(data.S2.Books) != len(data.ExpectedSlice) {
t.Fatalf("Got %d elements in slice, but expected %d", len(data.S2.Books), len(data.ExpectedSlice))
}
for i, val := range data.S2.Books {
if val != data.ExpectedSlice[i] {
t.Fatalf("Expected %s, but got %s while merging slice with override", data.ExpectedSlice[i], val)
}
}
}
}
6 changes: 5 additions & 1 deletion merge.go
Expand Up @@ -132,7 +132,11 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co
}
}
case reflect.Slice:
dst.Set(reflect.AppendSlice(dst, src))
if !isEmptyValue(src) && (overwrite || isEmptyValue(dst)) {
dst.Set(src)
} else {
dst.Set(reflect.AppendSlice(dst, src))
}
case reflect.Ptr:
fallthrough
case reflect.Interface:
Expand Down

0 comments on commit 1ab68ab

Please sign in to comment.