mirror of https://github.com/spf13/cast.git
Add ToIntSlice
This commit is contained in:
parent
2318c5caf2
commit
5db8dfc0bf
5
cast.go
5
cast.go
|
@ -56,3 +56,8 @@ func ToStringSlice(i interface{}) []string {
|
||||||
v, _ := ToStringSliceE(i)
|
v, _ := ToStringSliceE(i)
|
||||||
return v
|
return v
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ToIntSlice(i interface{}) []int {
|
||||||
|
v, _ := ToIntSliceE(i)
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
|
|
@ -77,6 +77,13 @@ func TestMaps(t *testing.T) {
|
||||||
assert.Equal(t, ToStringMapBool(stringMapBool), map[string]bool{"v1": true, "v2": false})
|
assert.Equal(t, ToStringMapBool(stringMapBool), map[string]bool{"v1": true, "v2": false})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSlices(t *testing.T) {
|
||||||
|
assert.Equal(t, []string{"a", "b"}, ToStringSlice([]string{"a", "b"}))
|
||||||
|
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([]interface{}{1.2, 3.2}))
|
||||||
|
}
|
||||||
|
|
||||||
func TestToBool(t *testing.T) {
|
func TestToBool(t *testing.T) {
|
||||||
assert.Equal(t, ToBool(0), false)
|
assert.Equal(t, ToBool(0), false)
|
||||||
assert.Equal(t, ToBool(nil), false)
|
assert.Equal(t, ToBool(nil), false)
|
||||||
|
|
20
caste.go
20
caste.go
|
@ -299,6 +299,26 @@ func ToStringSliceE(i interface{}) ([]string, error) {
|
||||||
return a, fmt.Errorf("Unable to Cast %#v to []string", i)
|
return a, fmt.Errorf("Unable to Cast %#v to []string", i)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func ToIntSliceE(i interface{}) ([]int, error) {
|
||||||
|
jww.DEBUG.Println("ToIntSliceE called on type:", reflect.TypeOf(i))
|
||||||
|
|
||||||
|
var a []int
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
func StringToDate(s string) (time.Time, error) {
|
func StringToDate(s string) (time.Time, error) {
|
||||||
return parseDateWith(s, []string{
|
return parseDateWith(s, []string{
|
||||||
time.RFC3339,
|
time.RFC3339,
|
||||||
|
|
Loading…
Reference in New Issue