GitHub Copilot 是一款由 AI 驱动的编程助手,能通过分析上下文实时生成代码建议。
GitHub Copilot基于生成式 AI 技术,通过学习海量代码库理解编程逻辑,为开发者提供动态解决方案,使用前需注册 GitHub 账户并获取 Copilot 许可证,安装编辑器插件并完成认证后即可使用。
1、代码补全
场景示例:用 Python 编写「石头剪刀布」游戏。
新建 rock_paper_scissor.py 文件,输入需求描述作为注释。
按回车后出现灰色幽灵代码(即 Copilot 建议),按 Tab 逐行接受建议。函数定义后,悬停代码可查看多套补全方案,或在「补全面板」中浏览选择。
最终添加函数调用语句,运行 python rock_paper_scissor.py 即可试玩。
2、内联聊天
功能升级:优化玩家输入灵活性。
选中代码行 player_choice = input('Rock, Paper, Scissors or Quit: ').lower(),按 Ctrl/Cmd + I 启动内联聊天。
输入指令:允许用户输入 r 代表石头,p 代表布,s 代表剪刀。
选择 AI 模型(如 Claude 3.5 Sonnet)后,Copilot 自动修改代码,接受改动后,终端测试即可用单字母操作。
3、Copilot 聊天
场景示例:为游戏添加图形界面。
打开 VS Code 左侧聊天图标,输入:用 Tkinter 创建简单 GUI。
确保当前文件已打开以提供上下文,选择模型后生成代码方案,通过「应用至编辑器」按钮一键替换代码,运行即可体验 GUI 版本。
4、斜杠命令
输入 / 可快速调用高频指令:
/explain:解释当前文件代码逻辑
/fix:自动修复代码错误
/tests:生成单元测试代码
/help:查看全部命令说明
5、添加上下文
通过变量增强 AI 理解:
#file filename.py:指定参考文件
#codebase:搜索整个代码库
6、专家协作 聊天参与者
输入 @ 召唤领域专家:
@workspace:分析整个项目结构
@terminal:结合终端日志诊断问题
@github:关联仓库与 Issue 数据
7、智能编辑
场景示例:添加详细计分板
点击 VS Code 的 Copilot 图标 →「打开 Copilot 编辑」,输入:添加统计平局、玩家胜局、电脑胜局的计分板。
选择模型生成方案,接受后 GUI 将自动更新统计模块。
8、提交与审查
智能提交:在 VS Code 源代码管理界面,点击「✨」图标自动生成语义化提交信息。
代码审查:选中代码后点击「✨」→「使用 Copilot 审查」,获取优化建议后再提交团队审核。
GitHub Copilot 官方定义: https://github.blog/ai-and-ml/github-copilot/github-for-beginners-essential-features-of-github-copilot/#what-is-github-copilot
免费许可证申请: http://gh.io/gfb-copilot
代码补全案例: https://github.blog/ai-and-ml/github-copilot/github-for-beginners-essential-features-of-github-copilot/#code-completion
内联聊天操作指南: https://github.blog/ai-and-ml/github-copilot/github-for-beginners-essential-features-of-github-copilot/#inline-chat
聊天功能解析: https://github.blog/ai-and-ml/github-copilot/github-for-beginners-essential-features-of-github-copilot/#copilot-chat
命令快捷方式: https://github.blog/ai-and-ml/github-copilot/github-for-beginners-essential-features-of-github-copilot/#slash-commands
上下文管理技巧: https://github.blog/ai-and-ml/github-copilot/github-for-beginners-essential-features-of-github-copilot/#adding-context
上下文变量文档: https://docs.github.com/en/copilot/using-github-copilot/copilot-chat/github-copilot-chat-cheat-sheet?tool=vscode#chat-variables
专家模式说明: https://github.blog/ai-and-ml/github-copilot/github-for-beginners-essential-features-of-github-copilot/#chat-participants
跨文件编辑案例: https://github.blog/ai-and-ml/github-copilot/github-for-beginners-essential-features-of-github-copilot/#copilot-edits
免费许可证申请: http://gh.io/gfb-copilot
官方文档: https://docs.github.com/en/copilot/using-github-copilot/best-practices-for-using-github-copilot
GitHub 社区: https://github.com/orgs/community/discussions/152688