Skip to content

Commit

Permalink
tpl/collections: Fix append when appending a slice to a slice of slices
Browse files Browse the repository at this point in the history
  • Loading branch information
bep committed Jun 13, 2023
1 parent 258884f commit deb3eaa
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
15 changes: 15 additions & 0 deletions common/collections/append.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,28 @@ func Append(to any, from ...any) (any, error) {
return Slice(from...), nil
}

// See issue #11004.
isToASliceOfSlices := tov.Len() > 0
for i := 0; i < tov.Len(); i++ {
v, isNil := indirect(tov.Index(i))
if isNil || v.Kind() != reflect.Slice {
isToASliceOfSlices = false
break
}
}

if isToASliceOfSlices {
return reflect.Append(tov, reflect.ValueOf(from)).Interface(), nil
}

for _, f := range from {
fv := reflect.ValueOf(f)
if !fv.Type().AssignableTo(tot) {
// Fall back to a []interface{} slice.
tov, _ := indirect(reflect.ValueOf(to))
return appendToInterfaceSlice(tov, from...)
}

tov = reflect.Append(tov, fv)
}

Expand Down
4 changes: 4 additions & 0 deletions tpl/collections/append_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ func TestAppend(t *testing.T) {
{[]string{"a", "b"}, []any{"c"}, []string{"a", "b", "c"}},
{[]string{"a", "b"}, []any{"c", "d", "e"}, []string{"a", "b", "c", "d", "e"}},
{[]string{"a", "b"}, []any{[]string{"c", "d", "e"}}, []string{"a", "b", "c", "d", "e"}},
// Issue #11004
{[]any{[]any{"a"}}, []any{"b"}, []any{[]any{"a"}, []any{"b"}}},
{[]any{[]any{"a"}, "b"}, []any{"c"}, []any{[]any{"a"}, "b", "c"}},

// Errors
{"", []any{[]string{"a", "b"}}, false},
{[]string{"a", "b"}, []any{}, false},
Expand Down

0 comments on commit deb3eaa

Please sign in to comment.