chore: unified parse mixed string and array

This commit is contained in:
Skyxim
2023-03-12 12:08:16 +08:00
parent 17fea4b459
commit 4b1e00d3aa
3 changed files with 47 additions and 37 deletions

View File

@ -1,5 +1,11 @@
package utils
import (
"errors"
"fmt"
"reflect"
)
func Filter[T comparable](tSlice []T, filter func(t T) bool) []T {
result := make([]T, 0)
for _, t := range tSlice {
@ -9,3 +15,20 @@ func Filter[T comparable](tSlice []T, filter func(t T) bool) []T {
}
return result
}
func ToStringSlice(value any) ([]string, error) {
strArr := make([]string, 0)
switch reflect.TypeOf(value).Kind() {
case reflect.Slice, reflect.Array:
origin := reflect.ValueOf(value)
for i := 0; i < origin.Len(); i++ {
item := fmt.Sprintf("%v", origin.Index(i))
strArr = append(strArr, item)
}
case reflect.String:
strArr = append(strArr, fmt.Sprintf("%v", value))
default:
return nil, errors.New("value format error, must be string or array")
}
return strArr, nil
}