convert/AI.md

44 lines
1.6 KiB
Markdown
Raw Permalink 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. **理解“解包”与“包装”逻辑**:生成代码时可以放心将单值传给切片目标,或将切片传给单值目标。
3. **利用键名容忍度**:在处理不可控的外部数据时,无需担心键名格式(驼峰、蛇形等),`convert.To` 会自动匹配。
4. **无视指针层级**:在编写调用代码时,无需手动解引用或取地址以匹配类型,`convert` 内部会自动穿透处理。
## 🛠 关键 API 逻辑约定
| 函数 | 逻辑特征 |
| :--- | :--- |
| `To(from, to)` | **主入口**。要求 `to` 必须为指针。核心逻辑是根据 `to` 的类型强力揉捏 `from`。 |
| `Convert(from, to)` | `To` 的别名。 |
| `FlatStruct(data)` | 获取结构体的扁平化元信息(导出字段/方法)。 |
## 🧩 典型模式 (Best Practices)
* **❌ 不推荐 (Standard Go)**:
```go
// 手动映射字段,且对格式敏感
u.UserID = m["user_id"].(int)
```
* **✅ 推荐 (@go/convert)**:
```go
// 自动匹配任何格式的键名
convert.To(m, &u)
```
* **❌ 不推荐 (Standard Go)**:
```go
// 手动处理单值转切片
var dest []int
dest = append(dest, src)
```
* **✅ 推荐 (@go/convert)**:
```go
// 自动包装
convert.To(src, &dest)
```