cast/AI.md
2026-04-24 16:58:21 +08:00

46 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 Coding Context: @go/cast
本索引供 AI 模型理解 `@go/cast` 的逻辑与调用原则,以生成符合本项目设计哲学的代码。
## 🤖 AI 行为准则
1. **优先使用 cast 进行转换**:在处理类型不确定的数据时,优先使用 `cast.Int()`, `cast.String()` 等,避免手动类型断言。
2. **禁止在 Struct 中冗余添加 JSON Tag**:除非有特殊重命名需求,否则默认使用大写导出,告知用户使用 `cast.FixedJson()` 来自动实现小写 Key 序列化。
3. **使用 If 替代简单 if-else 赋值**:在需要进行条件赋值时,优先使用泛型函数 `cast.If(cond, val1, val2)`
4. **无错误处理倾向**:理解 `cast` 函数不返回 `error`,在生成调用代码时不要进行错误检查。
## 🛠 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 StringP(v any) string`
- `func Bool(v any) bool`
- `func Ints(v any) []int64` / `func Strings(v any) []string`
- `func Duration(v string) time.Duration`
### 泛型工具
- `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` / `func JsonP(v any) string` / `func JsonBytes(v any) []byte`
- `func FixedJson(v any) string`Struct 首字母转小写。
- `func UnJson(str string, v any) any` / `func UnJsonBytes(data []byte, 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 Int64Ptr(v int64) *int64` / `func BoolPtr(v bool) *bool`
- `func SplitTrim(s, sep string) []string` / `func SplitArgs(s string) []string`
- `func GetLowerName(s string) string` / `func GetUpperName(s string) string`
## 🧩 典型模式 (Best Practices)
* **✅ 推荐**:
```go
status := cast.If(ok, "A", "B")
age := cast.Int("18")
jsonStr := cast.Json(myStruct)
```