From 2d31b9824cbb3b129d4848e786be5187f6fb0620 Mon Sep 17 00:00:00 2001 From: Lien li Date: Fri, 25 Mar 2022 13:06:20 +0800 Subject: [PATCH] support-convert-slice-to-int64 --- cast.go | 6 ++++++ cast_test.go | 34 ++++++++++++++++++++++++++++++++++ caste.go | 29 +++++++++++++++++++++++++++++ 3 files changed, 69 insertions(+) diff --git a/cast.go b/cast.go index 0cfe941..5dfc73c 100644 --- a/cast.go +++ b/cast.go @@ -169,6 +169,12 @@ func ToIntSlice(i interface{}) []int { return v } +// ToInt64Slice casts an interface to a []int64 type. +func ToInt64Slice(i interface{}) []int64 { + v, _ := ToInt64SliceE(i) + return v +} + // ToDurationSlice casts an interface to a []time.Duration type. func ToDurationSlice(i interface{}) []time.Duration { v, _ := ToDurationSliceE(i) diff --git a/cast_test.go b/cast_test.go index c254c57..2010d6a 100644 --- a/cast_test.go +++ b/cast_test.go @@ -1014,6 +1014,40 @@ func TestToIntSliceE(t *testing.T) { } } +func TestToInt64SliceE(t *testing.T) { + tests := []struct { + input interface{} + expect []int64 + iserr bool + }{ + {[]int{1, 3}, []int64{1, 3}, false}, + {[]interface{}{1.2, 3.2}, []int64{1, 3}, false}, + {[]string{"2", "3"}, []int64{2, 3}, false}, + {[2]string{"2", "3"}, []int64{2, 3}, false}, + // errors + {nil, nil, true}, + {testing.T{}, nil, true}, + {[]string{"foo", "bar"}, nil, true}, + } + + for i, test := range tests { + errmsg := fmt.Sprintf("i = %d", i) // assert helper message + + v, err := ToInt64SliceE(test.input) + if test.iserr { + assert.Error(t, err, errmsg) + continue + } + + assert.NoError(t, err, errmsg) + assert.Equal(t, test.expect, v, errmsg) + + // Non-E test + v = ToInt64Slice(test.input) + assert.Equal(t, test.expect, v, errmsg) + } +} + func TestToSliceE(t *testing.T) { tests := []struct { input interface{} diff --git a/caste.go b/caste.go index c04af6a..af1f00c 100644 --- a/caste.go +++ b/caste.go @@ -1184,6 +1184,35 @@ func ToStringSliceE(i interface{}) ([]string, error) { } } +// ToIntSliceE casts an interface to a []int64 type. +func ToInt64SliceE(i interface{}) ([]int64, error) { + if i == nil { + return []int64{}, fmt.Errorf("unable to cast %#v of type %T to []int", i, 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 of type %T to []int", i, i) + } + a[j] = val + } + return a, nil + default: + return []int64{}, fmt.Errorf("unable to cast %#v of type %T to []int", i, i) + } +} + // ToIntSliceE casts an interface to a []int type. func ToIntSliceE(i interface{}) ([]int, error) { if i == nil {