当前位置:网站首页>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
边栏推荐
- Action after deleting laravel's model
- Which MySQL functions are currently supported by tablestore in table storage?
- IM即時通訊開發實現心跳保活遇到的問題
- 最新NLP赛事实践总结!
- Comment win11 définit - il les permissions de l'utilisateur? Win11 comment définir les permissions de l'utilisateur
- In the past six months, it has been invested by five "giants", and this intelligent driving "dark horse" is sought after by capital
- Uncover the "intelligence tax" of mousse: spend 4billion on marketing, and only 7 invention patents
- 芯片供应转向过剩,中国芯片日产增加至10亿,国外芯片将更难受
- vim用户自动命令示例
- Submission lottery - light application server essay solicitation activity (may) award announcement
猜你喜欢

Malaysia's Star: Sun Yuchen is still adhering to the dream of digital economy in WTO MC12

ATSS:自动选择样本,消除Anchor based和Anchor free物体检测方法之间的差别

德国iF多项大奖加冕,这副耳机有多强?音珀GTW 270 Hybrid深度评测

Please, stop painting star! This has nothing to do with patriotism!

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

DO280管理应用部署--pod调度控制

How to use MySQL language for row and column devices?

Submission lottery - light application server essay solicitation activity (may) award announcement
![[IDM] IDM downloader installation](/img/2b/baf8852b422c1c4a18e9c60de864e5.png)
[IDM] IDM downloader installation
![[nodemon] app crashed - waiting for file changes before starting...解决方法](/img/ee/9830afd86e092851a2a906cb994949.png)
[nodemon] app crashed - waiting for file changes before starting...解决方法
随机推荐
复杂度相关OJ题(LeetCode、C语言、复杂度、消失的数字、旋转数组)
综述 | 激光与视觉融合SLAM
ADS算力芯片的多模型架构研究
【LeetCode】43. 字符串相乘
程序员职业生涯真的很短吗?
Nuxt.js数据预取
【观察】数字化时代的咨询往何处走?软通咨询的思与行
[open source data] open source data set for cross modal (MRI, Meg, eye movement) human spatial memory research based on virtual reality scenes
2023 spring recruitment Internship - personal interview process and face-to-face experience sharing
圈铁发音,动感与无噪强强出彩,魔浪HIFIair蓝牙耳机测评
The picgo shortcut is amazing. This person thinks exactly the same as me
She is the "HR of others" | ones character
【Hot100】19. Delete the penultimate node of the linked list
u本位合约和币本位合约有区别,u本位合约会爆仓吗
Principle of motion capture system
Action after deleting laravel's model
Problems encountered in IM instant messaging development to maintain heartbeat
Smart Party Building: faith through time and space | 7.1 dedication
高端程序员上班摸鱼指南
Korean AI team plagiarizes shock academia! One tutor with 51 students, or plagiarism recidivist