diff --git a/slice.go b/slice.go index e6a8328..c1e1f0d 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 fb7597c..57b5c58 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},