当前位置:网站首页>Go 语言怎么优化重复的 if err != nil 样板代码?
Go 语言怎么优化重复的 if err != nil 样板代码?
2022-07-01 16:11:00 【frank.】
大家好,我是 frank。
01
介绍
Go 语言的错误处理在社区中一直被部分 Go 开发者诟病,其中重复的 if err != nil 样板代码是最令 Go 开发者难以忍受的,严重降低代码的可读性。
针对这个社区争论非常激烈的话题,笔者介绍两种优化重复的 if err != nil 样板代码的方式。
02
封装错误检查函数
错误检查函数示例代码:
func CheckErrors (err error) {
if err != nil {
// do something
}
}
调用错误检查函数示例代码:
err := SomeMethod()
CheckErrors(err)
阅读上面这段代码,封装一个错误检查的函数,代码中需要处理错误的地方,直接调用该函数。
这种方式,虽然在视觉上提升了代码的可读性,但是在需要特殊处理错误的场景也有局限性,比如需要使用额外的信息完善错误时,该方式并不适用此类场景。
03
结构体中定义错误信息字段
我们可以在结构体中定义错误信息字段,将结构体的方法与错误信息绑定在一起。
示例代码:
type Writer struct {
err error
buf []byte
n int
wr io.Writer
}
func (b *Writer) Flush() error {
if b.err != nil {
return b.err
}
// ...
return nil
}
阅读 Go 标准库 bufio 的代码片段,我们可以发现在 Writer 结构体中定义一个 err 字段,将错误信息封装在结构体中。
在 Writer 结构体的方法的开头先判断 err 字段是否为 nil,如果 err 字段的值不是 nil,则直接返回 err,从而减少 if err != nil 样板代码的重复出现。
04
总结
本文我们介绍怎么优化 Go 语言中重复的 if err != nil 样板代码的两种方式,笔者推荐使用第二种方式,因为第一种方式虽然简单,但是在一些特定场景并不适合。
通过在结构体中定义错误信息的字段,将结构体的方法和错误信息绑定在一起的优化方式,相比较第一种方式更加优雅。
参考资料:
- https://www.reddit.com/r/golang/comments/6v07ij/copypasting_if_err_nil_return_err_everywhere/
- https://www.reddit.com/r/golang/comments/649o0c/syncx_go_library_that_extends_standard_sync/
- https://go.dev/blog/errors-are-values
- https://pkg.go.dev/golang.org/x/sync/errgroup
- https://pkg.go.dev/github.com/facebookgo/stackerr#section-readme
边栏推荐
- C#/VB. Net merge PDF document
- idea启动Command line is too long问题处理
- [open source data] open source data set for cross modal (MRI, Meg, eye movement) human spatial memory research based on virtual reality scenes
- Overview | slam of laser and vision fusion
- 【每日一题】1175. 质数排列
- Crypto Daily:孙宇晨在MC12上倡议用数字化技术解决全球问题
- Learn selenium to simulate mouse operation, and you can be lazy a little bit
- Please, stop painting star! This has nothing to do with patriotism!
- Problems encountered in IM instant messaging development to maintain heartbeat
- IM即时通讯开发万人群聊消息投递方案
猜你喜欢

Talking from mlperf: how to lead the next wave of AI accelerator

【IDM】IDM下载器安装

苹果自研基带芯片再次失败,说明了华为海思的技术领先性

HR interview: the most common interview questions and technical answers

Vscode find and replace the data of all files in a folder

【观察】数字化时代的咨询往何处走?软通咨询的思与行

自動、智能、可視!深信服SSLO方案背後的八大設計

电脑照片尺寸如何调整成自己想要的

Automatique, intelligent, visuel! Forte conviction des huit conceptions derrière la solution sslo

AVL 平衡二叉搜索树
随机推荐
分享在大疆DJI(深圳总部)工作的日常和福利
HR interview: the most common interview questions and technical answers
表格存储中tablestore 目前支持mysql哪些函数呢?
投稿开奖丨轻量应用服务器征文活动(5月)奖励公布
Win11如何设置用户权限?Win11设置用户权限的方法
【IDM】IDM下载器安装
圈铁发音,动感与无噪强强出彩,魔浪HIFIair蓝牙耳机测评
揭秘慕思“智商税”:狂砸40亿搞营销,发明专利仅7项
Principle of motion capture system
In the era of super video, what kind of technology will become the base?
【Hot100】19. 删除链表的倒数第 N 个结点
StoneDB 为国产数据库添砖加瓦,基于 MySQL 的一体化实时 HTAP 数据库正式开源!
Factory high-precision positioning management system, digital safety production management
Im instant messaging develops a message delivery scheme for 10000 people
【LeetCode】43. 字符串相乘
Research on multi model architecture of ads computing power chip
Motion capture system for apple picking robot
Korean AI team plagiarizes shock academia! One tutor with 51 students, or plagiarism recidivist
[IDM] IDM downloader installation
最新NLP赛事实践总结!