Path: blob/main/vendor/github.com/spf13/cast/slice.go
2875 views
// Copyright © 2014 Steve Francia <[email protected]>.1//2// Use of this source code is governed by an MIT-style3// license that can be found in the LICENSE file.45package cast67import (8"fmt"9"reflect"10"strings"11)1213// ToSliceE casts any value to a []any type.14func ToSliceE(i any) ([]any, error) {15i, _ = indirect(i)1617var s []any1819switch v := i.(type) {20case []any:21// TODO: use slices.Clone22return append(s, v...), nil23case []map[string]any:24for _, u := range v {25s = append(s, u)26}2728return s, nil29default:30return s, fmt.Errorf(errorMsg, i, i, s)31}32}3334func toSliceE[T Basic](i any) ([]T, error) {35v, ok, err := toSliceEOk[T](i)36if err != nil {37return nil, err38}3940if !ok {41return nil, fmt.Errorf(errorMsg, i, i, []T{})42}4344return v, nil45}4647func toSliceEOk[T Basic](i any) ([]T, bool, error) {48i, _ = indirect(i)49if i == nil {50return nil, true, fmt.Errorf(errorMsg, i, i, []T{})51}5253switch v := i.(type) {54case []T:55// TODO: clone slice56return v, true, nil57}5859kind := reflect.TypeOf(i).Kind()60switch kind {61case reflect.Slice, reflect.Array:62s := reflect.ValueOf(i)63a := make([]T, s.Len())6465for j := 0; j < s.Len(); j++ {66val, err := ToE[T](s.Index(j).Interface())67if err != nil {68return nil, true, fmt.Errorf(errorMsg, i, i, []T{})69}7071a[j] = val72}7374return a, true, nil75default:76return nil, false, nil77}78}7980// ToStringSliceE casts any value to a []string type.81func ToStringSliceE(i any) ([]string, error) {82if a, ok, err := toSliceEOk[string](i); ok {83if err != nil {84return nil, err85}8687return a, nil88}8990var a []string9192switch v := i.(type) {93case string:94return strings.Fields(v), nil95case any:96str, err := ToStringE(v)97if err != nil {98return nil, fmt.Errorf(errorMsg, i, i, a)99}100101return []string{str}, nil102default:103return nil, fmt.Errorf(errorMsg, i, i, a)104}105}106107108