...
1 package castx
2
3 import (
4 "fmt"
5 "reflect"
6 "strings"
7
8 "github.com/ory/x/stringslice"
9 "github.com/ory/x/stringsx"
10
11 "github.com/spf13/cast"
12 )
13
14
15 func ToFloatSlice(i interface{}) []float64 {
16 f, _ := ToFloatSliceE(i)
17 return f
18 }
19
20
21 func ToFloatSliceE(i interface{}) ([]float64, error) {
22 if i == nil {
23 return []float64{}, fmt.Errorf("unable to cast %#v of type %T to []float64", i, i)
24 }
25
26 switch v := i.(type) {
27 case []float64:
28 return v, nil
29 }
30
31 kind := reflect.TypeOf(i).Kind()
32 switch kind {
33 case reflect.Slice, reflect.Array:
34 s := reflect.ValueOf(i)
35 a := make([]float64, s.Len())
36 for j := 0; j < s.Len(); j++ {
37 val, err := cast.ToFloat64E(s.Index(j).Interface())
38 if err != nil {
39 return []float64{}, fmt.Errorf("unable to cast %#v of type %T to []float64", i, i)
40 }
41 a[j] = val
42 }
43 return a, nil
44 default:
45 return []float64{}, fmt.Errorf("unable to cast %#v of type %T to []float64", i, i)
46 }
47 }
48
49
50 func ToStringSlice(i interface{}) []string {
51 s, _ := ToStringSliceE(i)
52 return s
53 }
54
55
56 func ToStringSliceE(i interface{}) ([]string, error) {
57 switch s := i.(type) {
58 case string:
59 if strings.Contains(s, ",") {
60 return stringslice.TrimSpaceEmptyFilter(stringsx.Splitx(s, ",")), nil
61 }
62 }
63
64 return cast.ToStringSliceE(i)
65 }
66
View as plain text