Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 21 additions & 4 deletions slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ package cast
import (
"fmt"
"reflect"
"slices"
"strings"
)

Expand All @@ -17,13 +18,29 @@ 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
return append(s, v...), nil
return slices.Clone(v), nil
case []map[string]any:
for _, u := range v {
s = append(s, u)
s = make([]any, len(v))
for idx, u := range v {
s[idx] = u
}

return s, nil
}

kind := reflect.TypeOf(i).Kind()
switch kind {
case reflect.Slice, reflect.Array:
val := reflect.ValueOf(i)
s = make([]any, val.Len())
for j := 0; j < val.Len(); j++ {
s[j] = val.Index(j).Interface()
}

return s, nil
Expand Down
5 changes: 5 additions & 0 deletions slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,11 @@ func TestSlice(t *testing.T) {
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},
{[]string{"foo", "bar"}, []any{"foo", "bar"}, false},
{[]int{1, 2}, []any{1, 2}, false},
{[]bool{true, false}, []any{true, false}, false},
{[2]string{"a", "b"}, []any{"a", "b"}, false},
{[2]int{10, 20}, []any{10, 20}, false},

// Failure cases
{nil, nil, true},
Expand Down