From 9b1b06389b8146cf86210ee21e93ae708b823ea6 Mon Sep 17 00:00:00 2001 From: Jun Zhang Date: Wed, 23 May 2018 17:48:11 +0800 Subject: [PATCH] feat(StringSlice): support cast string to string slice by comma (#1) --- cast_test.go | 4 ++++ caste.go | 9 ++++++++- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/cast_test.go b/cast_test.go index d9b0b01..92d3cd2 100644 --- a/cast_test.go +++ b/cast_test.go @@ -974,6 +974,10 @@ func TestToStringSliceE(t *testing.T) { {[]string{"a", "b"}, []string{"a", "b"}, false}, {[]interface{}{1, 3}, []string{"1", "3"}, false}, {interface{}(1), []string{"1"}, false}, + {"a", []string{"a"}, false}, + {"a b", []string{"a", "b"}, false}, + {"a,b", []string{"a", "b"}, false}, + {"a b,c", []string{"a", "b,c"}, false}, // errors {nil, nil, true}, {testing.T{}, nil, true}, diff --git a/caste.go b/caste.go index 4fe1928..c136906 100644 --- a/caste.go +++ b/caste.go @@ -1049,7 +1049,14 @@ func ToStringSliceE(i interface{}) ([]string, error) { case []string: return v, nil case string: - return strings.Fields(v), nil + slice := strings.Fields(v) + // if the string can be splited by white space + // return slice immediately + if len(slice) > 1 { + return slice, nil + } + // otherwise, try to split string by comma + return strings.Split(v, ","), nil case interface{}: str, err := ToStringE(v) if err != nil {