support-convert-slice-to-int64

This commit is contained in:
Lien li 2022-03-25 13:06:20 +08:00
parent 88075729b0
commit 2d31b9824c
3 changed files with 69 additions and 0 deletions

View File

@ -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)

View File

@ -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{}

View File

@ -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 {