From 624889cda62596e5b3f11babeab55ecca0e1cb21 Mon Sep 17 00:00:00 2001 From: Fabio Falzoi Date: Wed, 22 Jun 2022 21:21:32 +0200 Subject: [PATCH] Add support for string to int slice conversion Signed-off-by: Fabio Falzoi --- cast_test.go | 5 +++++ caste.go | 11 +++++++++++ 2 files changed, 16 insertions(+) diff --git a/cast_test.go b/cast_test.go index dc8ba14..8aa96e7 100644 --- a/cast_test.go +++ b/cast_test.go @@ -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 { diff --git a/caste.go b/caste.go index 514d759..809fb4d 100644 --- a/caste.go +++ b/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()