github.com/kelleygo/clashcore@v1.0.2/common/utils/slice.go (about)

     1  package utils
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"reflect"
     7  )
     8  
     9  func Filter[T comparable](tSlice []T, filter func(t T) bool) []T {
    10  	result := make([]T, 0)
    11  	for _, t := range tSlice {
    12  		if filter(t) {
    13  			result = append(result, t)
    14  		}
    15  	}
    16  	return result
    17  }
    18  
    19  func ToStringSlice(value any) ([]string, error) {
    20  	strArr := make([]string, 0)
    21  	switch reflect.TypeOf(value).Kind() {
    22  	case reflect.Slice, reflect.Array:
    23  		origin := reflect.ValueOf(value)
    24  		for i := 0; i < origin.Len(); i++ {
    25  			item := fmt.Sprintf("%v", origin.Index(i))
    26  			strArr = append(strArr, item)
    27  		}
    28  	case reflect.String:
    29  		strArr = append(strArr, fmt.Sprintf("%v", value))
    30  	default:
    31  		return nil, errors.New("value format error, must be string or array")
    32  	}
    33  	return strArr, nil
    34  }