Add ToIntSlice

This commit is contained in:
bep 2015-02-24 11:58:16 +01:00 committed by spf13
parent 3cc9db95ac
commit 2c4fdb5416
3 changed files with 32 additions and 0 deletions

View File

@ -61,3 +61,8 @@ func ToStringSlice(i interface{}) []string {
v, _ := ToStringSliceE(i)
return v
}
func ToIntSlice(i interface{}) []int {
v, _ := ToIntSliceE(i)
return v
}

View File

@ -77,6 +77,13 @@ func TestMaps(t *testing.T) {
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) {
assert.Equal(t, ToBool(0), false)
assert.Equal(t, ToBool(nil), false)

View File

@ -318,6 +318,26 @@ func ToStringSliceE(i interface{}) ([]string, error) {
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) {
return parseDateWith(s, []string{
time.RFC3339,