cast/README.md

77 lines
2.9 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.

# @go/cast
> **Maintainer Statement:** 本项目完全由 AI 维护。任何改动均遵循代码质量与性能的最佳实践。
## 🎯 设计哲学
`@go/cast` 是一个为“敏捷开发”设计的 Go 基础工具库。其核心目标是**消除类型摩擦**,让开发者在处理数据时更关注“我想要什么”而不是“原本是什么”。
* **语义化 API**:通过 `To[T]` (严格/含错) 配合 `Quiet` (静默) 或 `Must` (断言) 提供一致的调用体验。
* **智能穿透**:自动识别 JSON 文本、结构体映射、KV 展开等复杂场景。
* **极致性能**:内置 FastEncoder/FastDecoder单路径处理最小化内存分配。
## 📦 安装
```bash
go get apigo.cc/go/cast
```
## 💡 快速开始
```go
import "apigo.cc/go/cast"
// 1. 语义化转换 (To[T] 返回错误)
val, err := cast.To[int]("123") // 123, nil
// 2. 摩擦消除工具 (Quiet 返回零值, Must 失败 Panic)
age := cast.Quiet(cast.To[int]("abc")) // 0
uid := cast.Must(cast.To[int]("100")) // 100
// 3. 快捷方式 (cast.As[T] 等价于 cast.Quiet(cast.To[T]))
name := cast.As[string](123) // "123"
// 4. 智能 JSON 自动转换
// 输入 map/struct -> 目标 string: 自动序列化
js := cast.As[string](map[string]int{"age": 18}) // `{"age":18}`
// 输入 string/[]byte -> 目标 struct/map: 自动反序列化
user, _ := cast.To[User](`{"name":"Tom"}`)
// 5. 复杂容器转换 (Map/Slice)
m, _ := cast.ToMap[string, int]([]any{"id", "1", "score", 100})
list := cast.As[[]int]([]string{"1", "2", "3"})
```
## 🛠 API 指南
### 核心语义 API
1. **通用转换**
* `To[T any](any) (T, error)` —— 万能转换入口。支持基础类型、Slice、Map 以及 JSON 的双向自动转换。
* `As[T any](any) T` —— 零摩擦转换快捷方式。失败时返回类型零值。
2. **错误处理工具**
* `Quiet[T any](T, error) T` —— 忽略错误,返回转换后的值(若有错则返回零值)。
* `Must[T any](T, error) T` —— 严谨模式。若有错误则直接 Panic常用于全局初始化。
3. **容器转换**
* `ToMap[K, V](any) (map[K]V, error)` —— 构建新 Map。
* `ToSlice[T](any) ([]T, error)` —— 构建新 Slice。
* `FillMap(target, source)` | `FillSlice(target, source)` —— 填充现有容器。
4. **JSON 序列化与构建**
* **编码**: `ToJSON(any) (string, error)` | `ToJSONBytes(any) ([]byte, error)`
* **解码**: `UnmarshalJSON(data, target) error` | `FromJSON[T](any) (T, error)`
* **进阶**: `ToJSONDesensitize(any, []string) (string, error)` (支持字段脱敏)
5. **泛型工具**
* `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` —— 快速构建索引 Map。
## 🧪 验证状态
测试全部通过,性能达标。详见:[TEST.md](./TEST.md)