From 60e080bec2f580317ccda06bb03ff2b40c3d749b Mon Sep 17 00:00:00 2001 From: houbaron Date: Wed, 7 Sep 2022 20:28:23 +0800 Subject: [PATCH] Add ToSliceE([]any) -> []interface{} --- cast_test.go | 4 ++++ caste.go | 22 +++++++++++++++------- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/cast_test.go b/cast_test.go index dc8ba14..2863ab4 100644 --- a/cast_test.go +++ b/cast_test.go @@ -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}, diff --git a/caste.go b/caste.go index 514d759..f2de75f 100644 --- a/caste.go +++ b/caste.go @@ -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) } }