3.2 KiB
3.2 KiB
@go/cast
Maintainer Statement: 本项目完全由 AI 维护。任何改动均遵循代码质量与性能的最佳实践。
🎯 设计哲学
@go/cast 是一个为“敏捷开发”设计的 Go 基础工具库。设计初衷是打破 Go 严苛类型系统带来的繁琐摩擦,在处理数据时更关注需要什么类型而不是原本是什么类型。
- 弱化类型摩擦:转换函数在失败时返回合理零值,专注业务流。
- 补足语言短板:提供泛型工具类补足 Go 语言无三元运算等缺陷。
- 去标签化:支持自动将 struct 字段名大写导出为小写,无需手动添加 JSON tag。
📦 安装
go get apigo.cc/go/cast
💡 快速开始
import "apigo.cc/go/cast"
// 像 JS 一样转换
age := cast.Int("18") // 18
// 泛型三元运算
status := cast.If(isAdmin, "Admin", "User")
// JSON 序列化增强
var u struct { UserID int }
cast.UnmarshalJSON("userId: 1001", &u) // u.UserID = 1001
cast.MustToJSON(u) // "userId": 1001,首字母自动小写
// 字符串切分增强
cast.Split(",", ",") // [],忽略无效切片
cast.Split("a, b, ", ",") // ["a", "b"],去除空白字符
🛠 API 指南
核心能力
-
基础转换(含多级指针穿透)
Int(any) int|Int64(any) int64Uint(any) uint|Uint64(any) uint64Float(any) float32|Float64(any) float64String(any) string|Bool(any) boolDuration(any) time.Duration
-
批量转换(Slice Casting)
Ints(any) []int64Strings(any) []string
-
泛型工具(Type Helpers)
If[T any](bool, T, T) T—— 三元逻辑In[T comparable]([]T, T) bool—— 包含判断Ptr[T any](T) *T—— 取指针ArrayToBoolMap[T comparable]([]T) map[T]bool—— 快速索引化
-
序列化(JSON & YAML)
- JSON 编码:
ToJSON(any)(string, error)|ToJSONDesensitize(any, []string)(string, error)|MustToJSON(any)string|PrettyToJSON(any)string - JSON 字节:
ToJSONBytes(any)([]byte, error)|ToJSONDesensitizeBytes(any, []string)([]byte, error)|MustJSONBytes(any)[]byte|PrettyToJSONBytes(any)[]byte - JSON 解码:
UnmarshalJSON(string, any)(any, error)|MustUnmarshalJSON(string, any)any|UnmarshalJSONBytes([]byte, any)(any, error)|MustUnmarshalJSONBytes([]byte, any)any - YAML 编码:
ToYAML(any)(string, error)|MustToYAML(any)string|YAMLBytes(any)([]byte, error)|MustYAMLBytes(any)[]byte - YAML 解码:
UnmarshalYAML(string, any)(any, error)|MustUnmarshalYAML(string, any)any|UnmarshalYAMLBytes([]byte, any)(any, error)|MustUnmarshalYAMLBytes([]byte, any)any
- JSON 编码:
-
辅助工具(Utilities)
- 切分:
Split(s, sep) []string|SplitArgs(s) []string - 拼接:
UniqueAppend([]string, ...any) []string|JoinArgs([]string, sep) string - 其他:
RealValue(reflect.Value) reflect.Value|GetLowerName(string) string|GetUpperName(string) string|FixUpperCase([]byte, []string)
- 切分:
🧪 验证状态
测试全部通过,性能达标。详见:TEST.md