From 282f7f441458146c8eca7a9e2233e9f87162eb3e Mon Sep 17 00:00:00 2001 From: Abhi Agarwal Date: Tue, 30 Aug 2016 19:36:22 -0400 Subject: [PATCH] Adding method to support int64 slice Adding small tests to test ToInt64Slice --- cast.go | 5 +++++ cast_test.go | 7 +++++++ caste.go | 31 +++++++++++++++++++++++++++++++ 3 files changed, 43 insertions(+) diff --git a/cast.go b/cast.go index de5a686..0f5cefd 100644 --- a/cast.go +++ b/cast.go @@ -76,3 +76,8 @@ func ToIntSlice(i interface{}) []int { v, _ := ToIntSliceE(i) return v } + +func ToInt64Slice(i interface{}) []int64 { + v, _ := ToInt64SliceE(i) + return v +} diff --git a/cast_test.go b/cast_test.go index 3fbcf87..d4cdaef 100644 --- a/cast_test.go +++ b/cast_test.go @@ -137,6 +137,13 @@ func TestSlices(t *testing.T) { 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"})) + + // ToInt64Slice tests + assert.Equal(t, []int64{1, 3}, ToInt64Slice([]int{1, 3})) + assert.Equal(t, []int64{1, 3}, ToInt64Slice([]interface{}{1.2, 3.2})) + assert.Equal(t, []int64{2, 3}, ToInt64Slice([]string{"2", "3"})) + assert.Equal(t, []int64{2, 3}, ToInt64Slice([2]string{"2", "3"})) + assert.Equal(t, []int64{2000000, 392233724}, ToInt64Slice([2]string{"2000000", "392233724"})) } func TestToBool(t *testing.T) { diff --git a/caste.go b/caste.go index 863585b..d708d5c 100644 --- a/caste.go +++ b/caste.go @@ -469,6 +469,37 @@ func ToIntSliceE(i interface{}) ([]int, error) { } } +// ToIntSliceE casts an empty interface to a []int. +func ToInt64SliceE(i interface{}) ([]int64, error) { + jww.TRACE.Println("ToInt64SliceE called on type:", reflect.TypeOf(i)) + + if i == nil { + return []int64{}, fmt.Errorf("Unable to Cast %#v to []int", i) + } + + switch v := i.(type) { + case []int64: + return v, nil + } + + kind := reflect.TypeOf(i).Kind() + switch kind { + case reflect.Slice, reflect.Array: + s := reflect.ValueOf(i) + a := make([]int64, s.Len()) + for j := 0; j < s.Len(); j++ { + val, err := ToInt64E(s.Index(j).Interface()) + if err != nil { + return []int64{}, fmt.Errorf("Unable to Cast %#v to []int64", i) + } + a[j] = val + } + return a, nil + default: + return []int64{}, fmt.Errorf("Unable to Cast %#v to []int64", i) + } +} + // StringToDate casts an empty interface to a time.Time. func StringToDate(s string) (time.Time, error) { return parseDateWith(s, []string{