Add support for string to int slice conversion

Signed-off-by: Fabio Falzoi <fabio.falzoi@isovalent.com>
This commit is contained in:
Fabio Falzoi 2022-06-22 21:21:32 +02:00
parent 2b0eb0f724
commit 624889cda6
2 changed files with 16 additions and 0 deletions

View File

@ -648,10 +648,15 @@ func TestToIntSliceE(t *testing.T) {
{[]interface{}{1.2, 3.2}, []int{1, 3}, false},
{[]string{"2", "3"}, []int{2, 3}, false},
{[2]string{"2", "3"}, []int{2, 3}, false},
{"", []int{}, false},
{"0", []int{0}, false},
{"1 2 3", []int{1, 2, 3}, false},
{"-1 -2 -3", []int{-1, -2, -3}, false},
// errors
{nil, nil, true},
{testing.T{}, nil, true},
{[]string{"foo", "bar"}, nil, true},
{"1 foo 2", nil, true},
}
for i, test := range tests {

View File

@ -1299,6 +1299,17 @@ func ToIntSliceE(i interface{}) ([]int, error) {
switch v := i.(type) {
case []int:
return v, nil
case string:
ss := strings.Fields(v)
a := make([]int, 0, len(ss))
for _, s := range ss {
v, err := strconv.Atoi(s)
if err != nil {
return []int{}, fmt.Errorf("unable to cast %#v of type %T to []int", i, i)
}
a = append(a, v)
}
return a, nil
}
kind := reflect.TypeOf(i).Kind()