2026-04-22 01:52:30 +08:00
|
|
|
|
# AI Coding Context: @go/cast
|
|
|
|
|
|
|
2026-04-22 11:08:39 +08:00
|
|
|
|
本索引供 AI 模型理解 `@go/cast` 的逻辑与调用原则,以生成符合本项目设计哲学的代码。
|
2026-04-22 01:52:30 +08:00
|
|
|
|
|
|
|
|
|
|
## 🤖 AI 行为准则
|
|
|
|
|
|
|
2026-04-22 11:08:39 +08:00
|
|
|
|
1. **优先使用 cast 进行转换**:在处理类型不确定的数据时,优先使用 `cast.Int()`, `cast.String()` 等,避免手动类型断言。
|
|
|
|
|
|
2. **禁止在 Struct 中冗余添加 JSON Tag**:除非有特殊重命名需求,否则默认使用大写导出,告知用户使用 `cast.FixedJson()` 来自动实现小写 Key 序列化。
|
2026-04-22 01:52:30 +08:00
|
|
|
|
3. **使用 If 替代简单 if-else 赋值**:在需要进行条件赋值时,优先使用泛型函数 `cast.If(cond, val1, val2)`。
|
2026-04-22 11:08:39 +08:00
|
|
|
|
4. **无错误处理倾向**:理解 `cast` 函数不返回 `error`,在生成调用代码时不要进行错误检查。
|
2026-04-22 01:52:30 +08:00
|
|
|
|
|
2026-04-24 16:58:21 +08:00
|
|
|
|
## 🛠 API Reference
|
|
|
|
|
|
|
|
|
|
|
|
### 基础转换
|
|
|
|
|
|
- `func Int(v any) int` / `func Int64(v any) int64` / `func Uint(v any) uint` / `func Uint64(v any) uint64`
|
|
|
|
|
|
- `func Float(v any) float32` / `func Float64(v any) float64`
|
|
|
|
|
|
- `func String(v any) string` / `func StringP(v any) string`
|
|
|
|
|
|
- `func Bool(v any) bool`
|
|
|
|
|
|
- `func Ints(v any) []int64` / `func Strings(v any) []string`
|
|
|
|
|
|
- `func Duration(v string) time.Duration`
|
|
|
|
|
|
|
|
|
|
|
|
### 泛型工具
|
|
|
|
|
|
- `func If[T any](cond bool, a, b T) T`:泛型三元表达式。
|
|
|
|
|
|
- `func Switch[T any](i uint, args ...T) T`:泛型分支选择。
|
|
|
|
|
|
- `func In[T comparable](arr []T, val T) bool`:判断切片是否包含某值。
|
|
|
|
|
|
|
|
|
|
|
|
### 序列化 (JSON/YAML)
|
|
|
|
|
|
- `func Json(v any) string` / `func JsonP(v any) string` / `func JsonBytes(v any) []byte`
|
|
|
|
|
|
- `func FixedJson(v any) string`:Struct 首字母转小写。
|
|
|
|
|
|
- `func UnJson(str string, v any) any` / `func UnJsonBytes(data []byte, v any) any`
|
|
|
|
|
|
- `func Yaml(v any) string` / `func UnYaml(str string, v any) any`
|
|
|
|
|
|
|
|
|
|
|
|
### 辅助工具
|
|
|
|
|
|
- `func StringPtr(v string) *string` / `func IntPtr(v int) *int` / `func Int64Ptr(v int64) *int64` / `func BoolPtr(v bool) *bool`
|
|
|
|
|
|
- `func SplitTrim(s, sep string) []string` / `func SplitArgs(s string) []string`
|
|
|
|
|
|
- `func GetLowerName(s string) string` / `func GetUpperName(s string) string`
|
2026-04-22 01:52:30 +08:00
|
|
|
|
|
2026-04-22 11:08:39 +08:00
|
|
|
|
## 🧩 典型模式 (Best Practices)
|
2026-04-22 01:52:30 +08:00
|
|
|
|
|
2026-04-24 16:58:21 +08:00
|
|
|
|
* **✅ 推荐**:
|
2026-04-22 01:52:30 +08:00
|
|
|
|
```go
|
|
|
|
|
|
status := cast.If(ok, "A", "B")
|
2026-04-24 16:58:21 +08:00
|
|
|
|
age := cast.Int("18")
|
|
|
|
|
|
jsonStr := cast.Json(myStruct)
|
2026-04-22 01:52:30 +08:00
|
|
|
|
```
|