cast/README.md

68 lines
2.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 关于本项目
本项目完全由 AI 维护。代码源自 github.com/ssgo/u 的重构。
# @go/cast
`@go/cast` 是一个为“敏捷开发”设计的 Go 基础工具库。它的设计初衷是打破 Go 语言严苛类型系统带来的繁琐摩擦,让开发者在处理数据转换时能够拥有类似 **JavaScript****PHP** 的丝滑体验。
## 🎯 设计哲学
* **弱化类型摩擦**`cast` 倾向于返回“合理的默认值”而不是错误,让你专注于核心业务流。
* **补足语言短板**:通过泛型工具类补齐了 Go 缺失的三元运算符。
* **去标签化 (No JSON Tags)**:支持自动处理大写导出规则,无需在每个结构体字段后手动添加 JSON tag。
* **数据直觉**:默认禁用 HTML 转义,保持序列化内容的原始色泽。
## 🛠 API Reference
### 基础转换函数
所有转换函数均会自动处理多级指针,并在转换失败时返回零值。
- `func Int(v any) int`
- `func Int64(v any) int64`
- `func Uint(v any) uint`
- `func Uint64(v any) uint64`
- `func Float(v any) float32`
- `func Float64(v any) float64`
- `func String(v any) string`
- `func Bool(v any) bool`
- `func Duration(v string) time.Duration` (支持 100ms 这种 DSL 格式)
### 泛型工具
- `func If[T any](cond bool, a, b T) T`:泛型三元运算符。
- `func Switch[T any](i uint, args ...T) T`:基于索引的选择。
- `func In[T comparable](arr []T, val T) bool`:判断切片是否包含某值。
### 现代化 JSON & YAML
- `func Json(v any) string`:高性能序列化,不转义 HTML 字符。
- `func JsonP(v any) string`:带缩进的格式化输出。
- `func FixedJson(v any) string`:自动将 Struct 字段首字母转为小写。
- `func UnJson(str string, v any) any`:反序列化。
- `func Yaml(v any) string`
- `func UnYaml(str string, v any) any`
### 指针辅助
- `func StringPtr(v string) *string`
- `func IntPtr(v int) *int`
- `func BoolPtr(v bool) *bool`
## 📦 安装
```bash
go get apigo.cc/go/cast
```
## 💡 快速开始
```go
import "apigo.cc/go/cast"
// 像 JS 一样转换
age := cast.Int("18") // 18
// 泛型三元运算
status := cast.If(isAdmin, "Admin", "User")
```