面向ChatGPT编程的11种方法:程序员必备ChatGPT使用技巧

0、搭建框架
首先,ChatGPT 可以帮我们开启想要编写的任何新内容的骨架结构,从而提升日常编码效率。GitHub Copilot 在这方面也做得很好。这里我们以远程下载图片为例进行演示。
在 VSCode 中,可以基于 ChatGPT 插件面向 ChatGPT 编程实现这段演示代码,代码生成后点击 Insert 自动插入代码到右侧编辑区:

当然,你也可以从第三方云存储下载图片丰富代码实现细节:

1、代码解释
你可以拿出想要理解的任何代码,比如上面这段 ChatGPT 自动生成的图片下载代码,让 ChatGPT 对其进行解释:

可以看到这些解释非常详细,这比自己摸索试图理解复杂的代码要快得多,尤其是一些比较抽象的、封装度比较高的底层代码。
2、改进现有的代码
通过描述你想要实现的目标,让 ChatGPT 对现有的代码进行改进。比如这里假设图片资源不存在,则退出不执行后面的文件保存操作:

它会为你提供如何实现目标的说明,包括修改后的代码,非常酷。
3、使用正确的命名规范重写代码
当重构由非本地 Go 开发人员编写的使用不同命名约定的代码时,这非常有用:


注意到 ChatGPT 不仅为你提供更新后的代码,还解释了更改的原因。
4、使用正确的代码风格重写代码
当审查(Review)和重构(Rewrite)由非本地 Go 开发人员编写的代码时,这非常有帮助。ChatGPT 熟知 Go 语言代码风格,并将为你提供改进代码的建议,使其更易于阅读:

5、简化代码
我们还可以让 ChatGPT 简化复杂的代码,结果将是原始代码的更紧凑版本,比如我们让 ChatGPT 来简化这段插入算法的示例代码:


你可以对比运行下两段代码的运行结果,完全一致,但是 ChatGPT 提供的简化版本显然代码更加简洁。
6、编写测试用例
这已经成为我最喜欢的 ChatGPT 功能之一:询问它是否可以帮助你测试一个函数,它将为你编写测试用例。还是以上面这个插入排序函数为例:


Go 测试用例中一般是不包含 main
函数的,你可以让 ChatGPT 中去掉 main
函数:

7、探索替代方案
有的时候,我们可能面对的是一段并不是性能最好的代码实现,比如基准测试后得出一段代码性能并不是很理想,需要寻求另一种更好的实现方式。这个时候,可以让 ChatGPT 给我们提供思路,当你想要探索不同的解决方案时,这非常有用。
下面以一段斐波那契数列的递归实现优化为例进行演示:


这里 ChatGPT 给出了两种替代方案,都很靠谱。
8、翻译代码
每当你想要将某些代码从一种语言转换到另一种语言时,可以请求 ChatGPT 帮助翻译,这对它来说是小菜一碟:

非常棒!
9、编写文档
这是我最喜欢的另一个技巧之一。询问 ChatGPT 编写代码的文档,它通常可以很好地完成。它甚至会将使用示例包括在文档中:

10、调试代码
如果你在代码中遇到困难并且找不到错误,可以向 ChatGPT 寻求帮助。它可能只需要几秒钟就能够找到错误原因所在。我不知道你的情况如何,但对我来说有时候会比 ChatGPT 要花费更长的时间。
我们以前面的下载图片为例进行演示:


不仅能找到问题,还能给出修复后的代码,调试代码的时间是不是大幅提升了呢?
总结
在面向 ChatGPT 编程的过程中,需要记住以下两点,这也是使用 ChatGPT 编程的两个大前提:
我拥有超过X年的编程经验,我知道我在做什么。
我不相信别人的代码(包括我的代码),我也不相信 ChatGPT 的输出。
使用 ChatGPT 不是说让它替我完成所有工作,使用 ChatGPT 是为了让我的产出和效率提升 10 倍。
ChatGPT 只是一个工具,而不是主导者,工具是给人使用的,能否最大化工具价值也在于使用它的人。主导者永远在人,在我。
何况,ChatGPT 也是有缺陷的。我发现它在处理代码时会出错,它不是总是对的,但这就是为什么我会在这里:监督它。我们一起形成了一个更完美的联盟。另外,那些诋毁这个工具的开发者正在忽略它的价值。
闪电发卡ChatGPT产品推荐:
ChatGPT Plus共享账号:https://www.chatgptzh.com/post/319.html
ChatGPT Plus独享账号(购买充值代充订阅):https://www.chatgptzh.com/post/306.html
ChatGPT APIKey购买充值(直连+转发):https://www.chatgptzh.com/post/305.html
ChatGPT Plus国内镜像逆向版:https://www.chatgptzh.com/post/312.html
ChatGPT国内版(AIChat):https://www.chatgptzh.com/post/318.html