很多人用 GitHub Copilot 的方式是:打开文件 → 开始写代码 → 等 Copilot 自动补全 → 按 Tab 接受。
这当然有用,但效率提升有限。真正让 Copilot 变成"AI 结对程序员"的关键,是学会写提示词——用注释引导 AI 输出你想要的代码。
Copilot 的补全基于上下文:文件内容、函数签名、变量名、注释。
注释是 Copilot 理解你意图的主要途径。一个清晰的注释,能让 Copilot 从"猜测你要写什么"变成"知道你要写什么"。
差的注释:
# sort function
def sort_list(data):
...
Copilot 可能生成:冒泡排序、快速排序、归并排序——你不知道它会选哪个。
好的注释:
# Sort a list of integers in descending order using quicksort
# Time complexity should be O(n log n) average case
# Do not modify the original list, return a new sorted list
def sort_list(data):
...
这样的注释,Copilot 几乎一定会生成一个符合你要求的快速排序实现。
# Calculate the total price of items in a shopping cart
# - Apply 10% discount if total > 100
# - Round result to 2 decimal places
# - Handle empty cart by returning 0.0
def calculate_total(cart_items):
...
明确输出格式、边界情况处理、业务规则。
# Convert a date string from "YYYY-MM-DD" to "MM/DD/YYYY"
# Example: "2026-07-21" -> "07/21/2026"
# Handle invalid input by returning None
def convert_date_format(date_str):
...
示例比描述更清晰,Copilot 能直接理解变换规则。
# Process user signup:
# 1. Validate email format (must contain @ and .)
# 2. Check if email already exists in database
# 3. Hash password with bcrypt
# 4. Insert new user record
# 5. Send welcome email
# Return (success: bool, error_message: str or None)
def process_signup(email, password):
...
把复杂任务拆成步骤,Copilot 会按顺序生成代码。
# Similar to the validate_token function in auth.py
# But check for admin role instead of user role
def validate_admin_token(token):
...
让 Copilot 参考已有代码风格和逻辑。
# Fetch user data from API
# - Raise ConnectionError if request fails after 3 retries
# - Raise ValueError if response JSON is missing "id" field
# - Return User object on success
def fetch_user(user_id):
...
明确异常类型和处理方式。
按 Ctrl+Shift+I 打开 Copilot Chat,先描述你要做什么,让 AI 帮你规划,再让它生成代码。比直接在文件里写注释更高效。
选中一段代码,按 Ctrl+Enter,Copilot 会弹出"内联补全"面板,提供多个候选方案,你可以选择最合适的。
选中一段代码,在 Copilot Chat 里输入"解释这段代码",它会给出逐行注释。适合理解别人写的代码或自己之前写的代码。
# Write unit tests for the calculate_total function above
# Use pytest framework
# Include test cases for: normal total, discount applied, empty cart
Copilot 会生成对应的测试代码。
Q:Copilot 生成的代码有 bug 怎么办?
A:Copilot 不保证代码正确。永远要 review、测试、调试。把它当作"快速出初稿"的工具,不是"交付可用代码"的工具。
Q:Copilot 不理解我的注释怎么办?
A:尝试拆分注释、增加示例、简化表述。注释越具体,Copilot 越容易理解。
Q:Copilot 生成的代码风格不一致怎么办?
A:在项目根目录添加 .github/copilot-instructions.md,定义项目的代码规范。Copilot 会参考这个文件。
下期预告:GitHub Copilot 实战指南③——Copilot Chat 深度用法,不只是聊天,是代码操作界面。
评论区