cast/README.md

77 lines
3.0 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 基础工具库。设计初衷是打破 Go 严苛类型系统带来的繁琐摩擦,在处理数据时更关注需要什么类型而不是原本是什么类型。
* **弱化类型摩擦**:转换函数在失败时返回合理零值,专注业务流。
* **补足语言短板**:提供泛型工具类补足 Go 语言无三元运算等缺陷。
* **去标签化**:支持自动将 struct 字段名大写导出为小写,无需手动添加 JSON tag。
## 📦 安装
```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")
// 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 指南
### 核心能力
1. **基础转换(含多级指针穿透)**
* `Int(any) int` | `Int64(any) int64`
* `Uint(any) uint` | `Uint64(any) uint64`
* `Float(any) float32` | `Float64(any) float64`
* `String(any) string` | `Bool(any) bool`
* `Duration(any) time.Duration`
2. **批量转换Slice Casting**
* `Ints(any) []int64`
* `Strings(any) []string`
3. **泛型工具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` —— 快速索引化
4. **序列化JSON & YAML**
* **JSON 编码**: `ToJSON(any)(string, error)` | `MustToJSON(any)string` | `PrettyToJSON(any)string`
* **JSON 字节**: `ToJSONBytes(any)([]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`
5. **辅助工具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](./TEST.md)