Skip to content

Feature: ToSlice #355

Description

@leaxoy

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
  }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions