Skip to content

Commit

Permalink
Override slices if WithOverride is specified
Browse files Browse the repository at this point in the history
  • Loading branch information
Austin Ouyang committed Mar 20, 2018
1 parent 0d4b488 commit e6c5cef
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
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,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 e6c5cef

Please sign in to comment.