From 2c4fdb5416dd394ff5e61fcdb8eb4f09e46a2ed8 Mon Sep 17 00:00:00 2001 From: bep Date: Tue, 24 Feb 2015 11:58:16 +0100 Subject: [PATCH] Add ToIntSlice --- cast.go | 5 +++++ cast_test.go | 7 +++++++ caste.go | 20 ++++++++++++++++++++ 3 files changed, 32 insertions(+) diff --git a/cast.go b/cast.go index fe382ca..1dde519 100644 --- a/cast.go +++ b/cast.go @@ -61,3 +61,8 @@ func ToStringSlice(i interface{}) []string { v, _ := ToStringSliceE(i) return v } + +func ToIntSlice(i interface{}) []int { + v, _ := ToIntSliceE(i) + return v +} diff --git a/cast_test.go b/cast_test.go index c428ba5..b4c8382 100644 --- a/cast_test.go +++ b/cast_test.go @@ -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) diff --git a/caste.go b/caste.go index 72c7690..db8b9fb 100644 --- a/caste.go +++ b/caste.go @@ -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,