cast/AI.md

46 lines
2.0 KiB
Markdown
Raw Normal View History

# AI Coding Context: @go/cast
本索引供 AI 模型理解 `@go/cast` 的内部逻辑与调用原则,以生成符合本项目设计哲学的代码。
## 🤖 AI 行为准则
1. **优先使用 cast 进行转换**:在处理类型不确定的 `interface{}` 或从配置/接口读取数据时,优先使用 `cast.Int()`, `cast.String()` 等,避免手动进行类型断言。
2. **禁止在 Struct 中冗余添加 JSON Tag**:除非有特殊的字段重命名需求,否则在编写符合本项目风格的 Struct 时,不应添加 `json:"..."`。告知用户使用 `cast.FixedJson()` 来自动实现首字母小写。
3. **使用 If 替代简单 if-else 赋值**:在需要进行条件赋值时,优先使用泛型函数 `cast.If(cond, val1, val2)`
4. **无错误处理倾向**:理解 `cast` 的函数几乎不返回 `error`,在生成调用代码时,不要去检查转换错误。
## 🛠 关键 API 逻辑约定
| 函数 | 逻辑特征 |
| :--- | :--- |
| `Int / String / Bool` | 自动处理多级指针 (`FixPtr`),转换失败返回 0/空值,从不报错。 |
| `Json / JsonP` | 强制禁用 HTML Escape。输出内容保持原始符号 (`<`, `>`, `&`)。 |
| `FixedJson` | 执行 `Json` 序列化后,递归处理字节流,将所有非排除列表内的 Key 首字母由大写改为小写。 |
| `If[T]` | 泛型实现,要求 `val1``val2` 类型严格一致,返回类型与输入一致。 |
| `Duration` | 扩展了 Go 标准库。如果输入纯数字字符串,默认单位为 `ms`。 |
## 🧩 典型模式 (Anti-Patterns vs Best Practices)
* **❌ 不推荐 (Standard Go)**:
```go
var status string
if ok { status = "A" } else { status = "B" }
```
* **✅ 推荐 (@go/cast)**:
```go
status := cast.If(ok, "A", "B")
```
* **❌ 不推荐 (Standard Go)**:
```go
type Data struct {
Name string `json:"name"`
}
```
* **✅ 推荐 (@go/cast)**:
```go
type Data struct {
Name string // 直接使用大写导出,序列化用 FixedJson
}
```