cast/AI.md

46 lines
1.7 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 逻辑约定
| 函数 | 逻辑特征 |
| :--- | :--- |
| `Int / String / Bool` | 自动处理多级指针,转换失败返回零值。 |
| `Json / JsonP` | 禁用 HTML Escape保持 `<` 等符号原始状态。 |
| `FixedJson` | 序列化后递归处理 Key将首字母由大写改为小写。 |
| `If[T]` | 泛型实现,要求 `val1``val2` 类型一致。 |
| `Duration` | 输入纯数字字符串时,默认单位为 `ms`。 |
## 🧩 典型模式 (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 // 直接使用大写导出
}
```