> For the complete documentation index, see [llms.txt](https://zhouhao4221.gitbook.io/haiqing-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://zhouhao4221.gitbook.io/haiqing-docs/04-prompt/code/code-generation.md).

# 代码生成

接口已定义，需要 AI 生成实现代码时使用。适合函数、模块、服务类。不适合核心业务规则（那类逻辑应人工编写）。

***

## 什么时候用

接口签名或类型定义已经写好，或者已有 REQ 文档描述了验收标准，现在需要生成实现代码。

不适合的场景：只有模糊的功能描述，接口还没定义——那种情况先用需求结构化或架构设计。

## 准备什么

* **接口定义**：函数签名、类型定义、API 契约。没有就先写一个，哪怕只是注释形式
* **类似实现示例**：代码库里 1-2 个风格相近的现有实现，让 AI 推断代码风格
* **约束**：不能引入的依赖、必须兼容的接口、技术栈限制
* **验收标准**：行为描述 + 边界条件。如果有 REQ 文档，直接引用

"类似实现示例"是最常被忽略的输入，也是最影响风格一致性的。没有它，AI 生成的代码会有正确但风格不融合的问题。

## 怎么触发

**单次任务**

```
先读 04-prompt/code/code-generation.md，
接口定义在 [文件路径]，
类似的现有实现参考 [文件路径]，
验收标准参考 [REQ 文件路径 / 直接描述]，
约束：[列出]。
请实现 [函数名/模块名]。
```

**写入 CLAUDE.md（推荐）**

```markdown
## 代码生成
实现新函数或模块时：
1. 先确认接口定义存在（没有则先写）
2. 找到代码库里 1-2 个类似实现作为风格参考
3. 不添加超出验收标准的功能
4. 所有外部依赖调用须处理失败情况
```

## 好的输出是什么样的

* 代码风格与提供的示例一致，不引入新的代码风格
* 严格遵守接口定义，不新增未定义的类型或参数
* 只实现验收标准要求的功能，不"顺手"加额外逻辑
* 代码后面有 3-5 句关键决策说明（为何这样处理错误、为何选择这个数据结构）
* 如果有约束冲突，先指出来再实现，不自行取舍

## 常见失败模式

* **风格不一致**：没有提供类似实现示例，AI 按通用风格生成。提前找好参考文件
* **过度实现**：AI 生成了验收标准之外的功能。在提示里明确说"不添加超出验收标准的功能"
* **忽略约束**：约束描述太模糊（"遵守项目规范"）。约束要具体，比如"不引入 goroutine，不使用 context 包"
* **遗留代码场景失效**：代码依赖大量隐式全局状态，AI 无法感知。先把相关全局状态显式化再生成

***

## 版本历史

* v1.0：初始版本
* v1.1：增加"类似实现示例"为必要输入说明，增加"过度实现"失败模式


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://zhouhao4221.gitbook.io/haiqing-docs/04-prompt/code/code-generation.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
