通用工具
泛型指针操作、切片查找、布尔值转换
通用工具
xUtil 提供泛型指针操作、切片查找、布尔值转换等通用工具函数。
Ptr
返回给定值的指针:
func Ptr[T any](data T) *T示例:
name := xUtil.Ptr("hello") // *string
age := xUtil.Ptr(18) // *int
enabled := xUtil.Ptr(true) // *bool
// nil 值返回 nil
var nilPtr *string = nil
result := xUtil.Ptr(nilPtr) // nil使用场景:
type User struct {
Name string
Nickname *string // 可选字段
}
// 快速创建可选字段
user := User{
Name: "张三",
Nickname: xUtil.Ptr("小张"),
}Val
从指针中安全地获取值,如果指针为 nil 则返回零值:
func Val[T any](ptr *T) T示例:
name := xUtil.Ptr("hello")
value := xUtil.Val(name) // "hello"
var nilPtr *string = nil
value2 := xUtil.Val(nilPtr) // ""(零值)
var nilInt *int = nil
value3 := xUtil.Val(nilInt) // 0(零值)使用场景:
type Config struct {
Timeout *int
}
func GetTimeout(cfg *Config) int {
// 安全获取可选配置,避免空指针
return xUtil.Val(cfg.Timeout)
}Contains
检查切片中是否包含指定元素:
func Contains[T comparable](slice []T, item T) bool示例:
// 整数切片
xUtil.Contains([]int{1, 2, 3}, 2) // true
xUtil.Contains([]int{1, 2, 3}, 4) // false
// 字符串切片
xUtil.Contains([]string{"a", "b", "c"}, "b") // true
xUtil.Contains([]string{"a", "b", "c"}, "d") // false使用场景:
allowedRoles := []string{"admin", "user", "guest"}
func CheckRole(role string) bool {
return xUtil.Contains(allowedRoles, role)
}ToBool
将字符串转换为布尔值,支持多种格式:
func ToBool(str string, defaultValue bool) bool支持的格式:
| 值 | 结果 |
|---|---|
true, 1, yes, on, enabled | true |
false, 0, no, off, disabled | false |
| 其他 | defaultValue |
示例:
xUtil.ToBool("true", false) // true
xUtil.ToBool("1", false) // true
xUtil.ToBool("yes", false) // true
xUtil.ToBool("enabled", false) // true
xUtil.ToBool("false", true) // false
xUtil.ToBool("0", true) // false
xUtil.ToBool("no", true) // false
xUtil.ToBool("disabled", true) // false
// 无法识别时返回默认值
xUtil.ToBool("invalid", true) // true
xUtil.ToBool("", false) // false使用场景:
func LoadConfig() {
// 从环境变量读取布尔配置
debugMode := xUtil.ToBool(os.Getenv("DEBUG"), false)
enableCache := xUtil.ToBool(os.Getenv("ENABLE_CACHE"), true)
}