mirror of https://github.com/spf13/cast.git
Add support for string to int slice conversion
Signed-off-by: Fabio Falzoi <fabio.falzoi@isovalent.com>
This commit is contained in:
parent
2b0eb0f724
commit
624889cda6
|
@ -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 {
|
||||
|
|
11
caste.go
11
caste.go
|
@ -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()
|
||||
|
|
Loading…
Reference in New Issue