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
4 changes: 4 additions & 0 deletions cast_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -682,6 +682,10 @@ func TestToSliceE(t *testing.T) {
}{
{[]interface{}{1, 3}, []interface{}{1, 3}, false},
{[]map[string]interface{}{{"k1": 1}, {"k2": 2}}, []interface{}{map[string]interface{}{"k1": 1}, map[string]interface{}{"k2": 2}}, false},
{[]int{1, 2}, []interface{}{1, 2}, false},
{[]struct{}{{}, {}}, []interface{}{struct{}{}, struct{}{}}, false},
{[]interface{}{nil, nil}, []interface{}{nil, nil}, false},
{[]*int{nil, nil}, []interface{}{(*int)(nil), (*int)(nil)}, false},
// errors
{nil, nil, true},
{testing.T{}, nil, true},
Expand Down
22 changes: 15 additions & 7 deletions caste.go
Original file line number Diff line number Diff line change
Expand Up @@ -1186,18 +1186,26 @@ func ToStringMapInt64E(i interface{}) (map[string]int64, error) {

// ToSliceE casts an interface to a []interface{} type.
func ToSliceE(i interface{}) ([]interface{}, error) {
var s []interface{}
if i == nil {
return nil, fmt.Errorf("unable to cast %#v of type %T to []interface{}", i, i)
}

switch v := i.(type) {
case []interface{}:
return append(s, v...), nil
case []map[string]interface{}:
for _, u := range v {
s = append(s, u)
return v, nil
}

kind := reflect.TypeOf(i).Kind()
switch kind {
case reflect.Slice, reflect.Array:
s := reflect.ValueOf(i)
a := make([]interface{}, s.Len())
for j := 0; j < s.Len(); j++ {
a[j] = s.Index(j).Interface()
}
return s, nil
return a, nil
default:
return s, fmt.Errorf("unable to cast %#v of type %T to []interface{}", i, i)
return nil, fmt.Errorf("unable to cast %#v of type %T to []interface{}", i, i)
}
}

Expand Down