mirror of https://github.com/spf13/cast.git
Make ToIntSliceE more flexible
Now it accepts any slice or array type that contains a type supported by ToIntE. [close #12]
This commit is contained in:
parent
2c4fdb5416
commit
4d07383ffe
|
@ -82,6 +82,8 @@ func TestSlices(t *testing.T) {
|
||||||
assert.Equal(t, []string{"1", "3"}, ToStringSlice([]interface{}{1, 3}))
|
assert.Equal(t, []string{"1", "3"}, ToStringSlice([]interface{}{1, 3}))
|
||||||
assert.Equal(t, []int{1, 3}, ToIntSlice([]int{1, 3}))
|
assert.Equal(t, []int{1, 3}, ToIntSlice([]int{1, 3}))
|
||||||
assert.Equal(t, []int{1, 3}, ToIntSlice([]interface{}{1.2, 3.2}))
|
assert.Equal(t, []int{1, 3}, ToIntSlice([]interface{}{1.2, 3.2}))
|
||||||
|
assert.Equal(t, []int{2, 3}, ToIntSlice([]string{"2", "3"}))
|
||||||
|
assert.Equal(t, []int{2, 3}, ToIntSlice([2]string{"2", "3"}))
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestToBool(t *testing.T) {
|
func TestToBool(t *testing.T) {
|
||||||
|
|
38
caste.go
38
caste.go
|
@ -321,21 +321,33 @@ func ToStringSliceE(i interface{}) ([]string, error) {
|
||||||
func ToIntSliceE(i interface{}) ([]int, error) {
|
func ToIntSliceE(i interface{}) ([]int, error) {
|
||||||
jww.DEBUG.Println("ToIntSliceE called on type:", reflect.TypeOf(i))
|
jww.DEBUG.Println("ToIntSliceE called on type:", reflect.TypeOf(i))
|
||||||
|
|
||||||
var a []int
|
if i == nil {
|
||||||
|
return []int{}, fmt.Errorf("Unable to Cast %#v to []int", i)
|
||||||
switch v := i.(type) {
|
|
||||||
case []interface{}:
|
|
||||||
for _, u := range v {
|
|
||||||
a = append(a, ToInt(u))
|
|
||||||
}
|
|
||||||
return a, nil
|
|
||||||
case []int:
|
|
||||||
return v, nil
|
|
||||||
default:
|
|
||||||
return a, fmt.Errorf("Unable to Cast %#v to []int", i)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return a, fmt.Errorf("Unable to Cast %#v to []int", i)
|
switch v := i.(type) {
|
||||||
|
case []int:
|
||||||
|
return v, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
kind := reflect.TypeOf(i).Kind()
|
||||||
|
switch kind {
|
||||||
|
case reflect.Slice, reflect.Array:
|
||||||
|
s := reflect.ValueOf(i)
|
||||||
|
a := make([]int, s.Len())
|
||||||
|
for j := 0; j < s.Len(); j++ {
|
||||||
|
val, err := ToIntE(s.Index(j).Interface())
|
||||||
|
if err != nil {
|
||||||
|
return []int{}, fmt.Errorf("Unable to Cast %#v to []int", i)
|
||||||
|
}
|
||||||
|
a[j] = val
|
||||||
|
}
|
||||||
|
return a, nil
|
||||||
|
default:
|
||||||
|
return []int{}, fmt.Errorf("Unable to Cast %#v to []int", i)
|
||||||
|
}
|
||||||
|
|
||||||
|
return []int{}, fmt.Errorf("Unable to Cast %#v to []int", i)
|
||||||
}
|
}
|
||||||
|
|
||||||
func StringToDate(s string) (time.Time, error) {
|
func StringToDate(s string) (time.Time, error) {
|
||||||
|
|
Loading…
Reference in New Issue