feat(StringSlice): support cast string to string slice by comma (#1)

This commit is contained in:
Jun Zhang 2018-05-23 17:48:11 +08:00 committed by GitHub
parent 8965335b8c
commit 9b1b06389b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 12 additions and 1 deletions

View File

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

View File

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