The current scope of application for the ToSlice method is too narrow, failing to cover many scenarios—for example:
type Users []User
ToSlice([]any{1,2,3,}) => []any{1, 2, 3}
ToSlice([]int{1,2,3,}) => []any{} // should []any{1,2,3}
ToSlice([]User{u1, u2}) => []any{} // should []any{u1, u2}
A possible new implementation:
func ToSliceE(v any) ([]any, error) {
if v == nil {
return nil, fmt.Errorf("nil")
}
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Slice && rv.Kind() != reflect.Array {
return nil, fmt.Errorf("not slice/array: %T", v)
}
out := make([]any, rv.Len())
for i := 0; i < rv.Len(); i++ {
out[i] = rv.Index(i).Interface()
}
return out, nil
}
The current scope of application for the
ToSlicemethod is too narrow, failing to cover many scenarios—for example:A possible new implementation: