Add ToSliceE([]any) -> []interface{}

This commit is contained in:
houbaron 2022-09-07 20:28:23 +08:00
parent 2b0eb0f724
commit 60e080bec2
2 changed files with 19 additions and 7 deletions

View File

@ -682,6 +682,10 @@ func TestToSliceE(t *testing.T) {
}{ }{
{[]interface{}{1, 3}, []interface{}{1, 3}, false}, {[]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}, {[]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 // errors
{nil, nil, true}, {nil, nil, true},
{testing.T{}, nil, true}, {testing.T{}, nil, true},

View File

@ -1186,18 +1186,26 @@ func ToStringMapInt64E(i interface{}) (map[string]int64, error) {
// ToSliceE casts an interface to a []interface{} type. // ToSliceE casts an interface to a []interface{} type.
func ToSliceE(i interface{}) ([]interface{}, error) { 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) { switch v := i.(type) {
case []interface{}: case []interface{}:
return append(s, v...), nil return v, nil
case []map[string]interface{}:
for _, u := range v {
s = append(s, u)
} }
return s, 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 a, nil
default: 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)
} }
} }