convert/AI.md

47 lines
1.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.

# AI Coding Context: @go/convert
本索引供 AI 模型理解 `@go/convert` 的设计逻辑,以生成符合本项目“意图优先、零摩擦”哲学的代码。
## 🤖 AI 行为准则
1. **优先使用 convert.To 进行对象映射**在需要进行结构体拷贝、Map 转 Struct 或复杂嵌套转换时,直接调用 `convert.To(from, &to)`
2. **不再建议手动编写冗余转换代码**:例如不需要手动循环切片来转换元素类型,`convert.To` 会自动完成。
3. **理解“解包”与“包装”逻辑**:生成代码时可以放心将单值传给切片目标,或将切片传给单值目标。
4. **利用键名容忍度**:在处理不可控的外部 Map 数据(如 API 响应)时,无需担心键名是 `camelCase` 还是 `snake_case``convert.To` 会自动匹配。
## 🛠 关键 API 逻辑约定
| 函数 | 逻辑特征 |
| :--- | :--- |
| `To(from, to)` | **主入口**`to` 必须为指针。支持所有基础类型、容器、函数及嵌套指针。失败会重置 `to` 为零值而不报错。 |
| `normalizeKey` | 内部逻辑:移除所有非字母数字字符并转小写。`My_User-ID` -> `myuserid`。 |
| `Func` 转换 | 动态代理。支持在不同签名的函数间建立桥接,并自动转换输入输出参数。 |
| `FlatStruct` | 工具。返回包含所有平展字段、方法及其 Value 的 `StructInfo`。 |
## 🧩 典型模式 (Best Practices)
* **❌ 不推荐 (Standard Go)**:
```go
// 手动循环并转换类型
dest := make([]int, len(src))
for i, v := range src {
dest[i] = int(cast.Int(v))
}
```
* **✅ 推荐 (@go/convert)**:
```go
// 一行搞定,自动处理所有摩擦
convert.To(src, &dest)
```
* **❌ 不推荐 (Standard Go)**:
```go
// 手动映射字段
u.UserID = m["user_id"].(int)
```
* **✅ 推荐 (@go/convert)**:
```go
// 自动忽略键名格式差异
convert.To(m, &u)
```