convert/AI.md
2026-04-24 16:58:23 +08:00

34 lines
1.4 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. **理解“解包”与“包装”逻辑**:生成代码时可以放心将单值传给切片目标,或将切片传给单值目标。
3. **利用键名容忍度**:在处理不可控的外部数据时,无需担心键名格式(驼峰、蛇形等),`convert.To` 会自动匹配。
4. **无视指针层级**:在编写调用代码时,无需手动解引用或取地址以匹配类型,`convert` 内部会自动穿透处理。
## 🛠 API Reference
### 核心转换函数
- `func To(from, to any)`:支持任意可能的类型深度转换,`to` 必须为指针。
### 结构体分析
- `func FlatStruct(data any) *StructInfo`:平展结构体(仅导出字段/方法)。
- `func FlatStructWithUnexported(data any) *StructInfo`:平展结构体(包含未导出字段/方法)。
## 🧩 典型模式 (Best Practices)
* **✅ 推荐 (@go/convert)**:
```go
// 自动匹配任何格式的键名
convert.To(from, &u)
```
* **✅ 推荐 (@go/convert)**:
```go
// 自动包装单值至切片
convert.To(src, &dest)
```