From 200f90d97053f846f603a88fa283dccc30198142 Mon Sep 17 00:00:00 2001 From: Heath Stewart Date: Mon, 16 May 2022 01:49:37 -0700 Subject: [PATCH] Support slices of same type Fixes #209 --- issue209_test.go | 26 ++++++++++++++++++++++++++ mergo.go | 4 ++-- mergo_test.go | 4 ++-- 3 files changed, 30 insertions(+), 4 deletions(-) create mode 100644 issue209_test.go diff --git a/issue209_test.go b/issue209_test.go new file mode 100644 index 0000000..00de234 --- /dev/null +++ b/issue209_test.go @@ -0,0 +1,26 @@ +package mergo_test + +import ( + "testing" + + "github.com/imdario/mergo" +) + +func TestIssue209(t *testing.T) { + dst := []string{"a", "b"} + src := []string{"c", "d"} + + if err := mergo.Merge(&dst, src, mergo.WithAppendSlice); err != nil { + t.Error(err) + } + + expected := []string{"a", "b", "c", "d"} + if len(dst) != len(expected) { + t.Errorf("arrays not equal length") + } + for i := range expected { + if dst[i] != expected[i] { + t.Errorf("array elements at %d are not equal", i) + } + } +} diff --git a/mergo.go b/mergo.go index 3cc926c..9fe362d 100644 --- a/mergo.go +++ b/mergo.go @@ -17,7 +17,7 @@ import ( var ( ErrNilArguments = errors.New("src and dst must not be nil") ErrDifferentArgumentsTypes = errors.New("src and dst must be of same type") - ErrNotSupported = errors.New("only structs and maps are supported") + ErrNotSupported = errors.New("only structs, maps, and slices are supported") ErrExpectedMapAsDestination = errors.New("dst was expected to be a map") ErrExpectedStructAsDestination = errors.New("dst was expected to be a struct") ErrNonPointerAgument = errors.New("dst must be a pointer") @@ -65,7 +65,7 @@ func resolveValues(dst, src interface{}) (vDst, vSrc reflect.Value, err error) { return } vDst = reflect.ValueOf(dst).Elem() - if vDst.Kind() != reflect.Struct && vDst.Kind() != reflect.Map { + if vDst.Kind() != reflect.Struct && vDst.Kind() != reflect.Map && vDst.Kind() != reflect.Slice { err = ErrNotSupported return } diff --git a/mergo_test.go b/mergo_test.go index d69714c..1259ec2 100644 --- a/mergo_test.go +++ b/mergo_test.go @@ -930,11 +930,11 @@ func TestMergeMapWithInnerSliceOfDifferentType(t *testing.T) { } } -func TestMergeSlicesIsNotSupported(t *testing.T) { +func TestMergeDifferentSlicesIsNotSupported(t *testing.T) { src := []string{"a", "b"} dst := []int{1, 2} - if err := mergo.Merge(&src, &dst, mergo.WithOverride, mergo.WithAppendSlice); err != mergo.ErrNotSupported { + if err := mergo.Merge(&src, &dst, mergo.WithOverride, mergo.WithAppendSlice); err != mergo.ErrDifferentArgumentsTypes { t.Errorf("expected %q, got %q", mergo.ErrNotSupported, err) } }