From 1a47b61b4f1382b8672804e6e3f8909a09520907 Mon Sep 17 00:00:00 2001 From: AdamMagued Date: Fri, 2 Oct 2026 15:12:29 +0000 Subject: [PATCH] feat: support arbitrary slices and arrays in ToSlice In ToSliceE, only []any and []map[string]any were explicitly handled in the type switch. When callers passed typed slices (such as []int, []string, or slices of custom structs) or fixed-size arrays, ToSliceE returned an error unable to cast to []any. Use reflection to inspect reflect.Slice and reflect.Array inputs, allocating a []any slice of corresponding length and converting each indexed element via Interface(). Add regression tests covering []int, []string, arrays, and struct slices. Fixes #355 --- slice.go | 14 ++++++++++++++ slice_test.go | 9 +++++++++ 2 files changed, 23 insertions(+) diff --git a/slice.go b/slice.go index e6a8328c..c1e1f0d7 100644 --- a/slice.go +++ b/slice.go @@ -17,6 +17,10 @@ func ToSliceE(i any) ([]any, error) { var s []any + if i == nil { + return s, fmt.Errorf(errorMsg, i, i, s) + } + switch v := i.(type) { case []any: // TODO: use slices.Clone @@ -28,6 +32,16 @@ func ToSliceE(i any) ([]any, error) { return s, nil default: + kind := reflect.TypeOf(i).Kind() + if kind == reflect.Slice || kind == reflect.Array { + rv := reflect.ValueOf(i) + out := make([]any, rv.Len()) + for idx := 0; idx < rv.Len(); idx++ { + out[idx] = rv.Index(idx).Interface() + } + return out, nil + } + return s, fmt.Errorf(errorMsg, i, i, s) } } diff --git a/slice_test.go b/slice_test.go index fb7597cc..57b5c58e 100644 --- a/slice_test.go +++ b/slice_test.go @@ -230,9 +230,18 @@ func TestUintSlice(t *testing.T) { } func TestSlice(t *testing.T) { + type user struct { + Name string + } + testCases := []testCase{ {[]any{1, 3}, []any{1, 3}, false}, {[]map[string]any{{"k1": 1}, {"k2": 2}}, []any{map[string]any{"k1": 1}, map[string]any{"k2": 2}}, false}, + {[]int{1, 2, 3}, []any{1, 2, 3}, false}, + {[]string{"a", "b"}, []any{"a", "b"}, false}, + {[3]int{1, 2, 3}, []any{1, 2, 3}, false}, + {[2]string{"a", "b"}, []any{"a", "b"}, false}, + {[]user{{"alice"}, {"bob"}}, []any{user{"alice"}, user{"bob"}}, false}, // Failure cases {nil, nil, true},