64 lines
1.3 KiB
Go
64 lines
1.3 KiB
Go
package common
|
|
|
|
import (
|
|
"fmt"
|
|
"runtime"
|
|
)
|
|
|
|
// InterfaceSliceToStringSlice 将 []interface{} 安全转换为 []string
|
|
func InterfaceSliceToStringSlice(slice []interface{}) []string {
|
|
result := make([]string, 0, len(slice))
|
|
for _, v := range slice {
|
|
if str, ok := v.(string); ok && str != "" {
|
|
result = append(result, str)
|
|
}
|
|
}
|
|
return result
|
|
}
|
|
|
|
// FormatBytes 格式化字节大小为人类可读格式
|
|
// 例如: 1024 → "1.00 KB", 1048576 → "1.00 MB"
|
|
func FormatBytes(bytes uint64) string {
|
|
const unit = 1024
|
|
if bytes < unit {
|
|
return fmt.Sprintf("%d B", bytes)
|
|
}
|
|
div, exp := int64(unit), 0
|
|
for n := bytes / unit; n >= unit; n /= unit {
|
|
div *= unit
|
|
exp++
|
|
}
|
|
return fmt.Sprintf("%.2f %cB", float64(bytes)/float64(div), "KMGTPE"[exp])
|
|
}
|
|
|
|
// Contains 检查切片是否包含元素
|
|
func Contains[T comparable](slice []T, item T) bool {
|
|
for _, s := range slice {
|
|
if s == item {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// Difference 返回在 a 中但不在 b 中的元素
|
|
func Difference[T comparable](a, b []T) []T {
|
|
mb := make(map[T]struct{}, len(b))
|
|
for _, x := range b {
|
|
mb[x] = struct{}{}
|
|
}
|
|
var diff []T
|
|
for _, x := range a {
|
|
if _, found := mb[x]; !found {
|
|
diff = append(diff, x)
|
|
}
|
|
}
|
|
return diff
|
|
}
|
|
|
|
// IsWindows 判断是否为Windows系统
|
|
func IsWindows() bool {
|
|
return runtime.GOOS == "windows"
|
|
}
|
|
|