当前位置:网站首页>How to optimize repeated if err in go language= Nil template code?
How to optimize repeated if err in go language= Nil template code?
2022-07-01 16:21:00 【frank.】
Hello everyone , I am a frank.
01
Introduce
Go Language error handling has been a part of the community Go Developer criticism , Which repeats if err != nil
Boilerplate code is the most interesting Go Developers can't stand , Seriously reduce the readability of the code .
A very heated topic in this community , The author introduces two optimization methods if err != nil
The way of boilerplate code .
02
Encapsulate the error checking function
Error checking function sample code :
func CheckErrors (err error) {
if err != nil {
// do something
}
}
Call the error checking function sample code :
err := SomeMethod()
CheckErrors(err)
Read the code above , Encapsulate an error checking function , Where errors need to be handled in the code , Call this function directly .
This way, , Although it improves the readability of the code visually , But there are also limitations in scenarios that require special error handling , For example, when you need to use additional information to improve the error , This method is not applicable to such scenarios .
03
Define the error information field in the structure
We can define the error information field in the structure , Bind the method of the structure with the error message .
Sample code :
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
}
read Go Standard library bufio Code snippet of , We can find it in Writer Define a in the structure err Field , Encapsulate the error information in the structure .
stay Writer At the beginning of the structure method, judge err Is the field nil, If err The value of the field is not nil, Then return directly err, Thereby reducing if err != nil
Repetition of boilerplate code .
04
summary
In this article, we introduce how to optimize Go Repeated in language if err != nil
Two ways of boilerplate code , The author recommends using the second method , Because the first way is simple , But it is not suitable for some specific scenes .
By defining the field of error information in the structure , The optimization method that binds the method of the structure with the error information , Compared with the first way, it is more elegant .
Reference material :
- 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
边栏推荐
- Go language learning notes - Gorm use - table addition, deletion, modification and query | web framework gin (VIII)
- 如何使用phpIPAM来管理IP地址和子网
- Origin2018安装与使用(整理中)
- The picgo shortcut is amazing. This person thinks exactly the same as me
- UML旅游管理系统「建议收藏」
- How long will it take to achieve digital immortality? Metacosmic holographic human avatar 8i
- How to use phpipam to manage IP addresses and subnets
- 红队第10篇:coldfusion反序列化过waf改exp拿靶标的艰难过程
- C#/VB. Net merge PDF document
- Authentication processing in interface testing framework
猜你喜欢
The sharp drop in electricity consumption in Guangdong shows that the substitution of high-tech industries for high-energy consumption industries has achieved preliminary results
Korean AI team plagiarizes shock academia! One tutor with 51 students, or plagiarism recidivist
韩国AI团队抄袭震动学界!1个导师带51个学生,还是抄袭惯犯
Uncover the "intelligence tax" of mousse: spend 4billion on marketing, and only 7 invention patents
高端程序员上班摸鱼指南
投稿开奖丨轻量应用服务器征文活动(5月)奖励公布
Endeavouros mobile hard disk installation
process.env.NODE_ENV
Problems encountered in IM instant messaging development to maintain heartbeat
怎麼用MySQL語言進行行列裝置?
随机推荐
Share the daily work and welfare of DJI (Shenzhen headquarters) in Dajiang
韩国AI团队抄袭震动学界!1个导师带51个学生,还是抄袭惯犯
Principes et applications du système de base de données (006) - - compilation et installation de MySQL 5.7 (environnement Linux)
UML旅游管理系统「建议收藏」
Use Tencent cloud to build a map bed service
Five years after graduation, I became a test development engineer with an annual salary of 30w+
如何使用phpIPAM来管理IP地址和子网
There is a difference between u-standard contract and currency standard contract. Will u-standard contract explode
Idea start command line is too long problem handling
ssm框架原理
Korean AI team plagiarizes shock academia! One tutor with 51 students, or plagiarism recidivist
When ABAP screen switching, refresh the previous screen
电脑屏幕变色了怎么调回来,电脑屏幕颜色怎么改
Action after deleting laravel's model
EndeavourOS移动硬盘安装
Research on multi model architecture of ads computing power chip
DO280管理应用部署--pod调度控制
Programming examples of stm32f1 and stm32subeide - production melody of PWM driven buzzer
Tutorial on principles and applications of database system (004) -- MySQL installation and configuration: resetting MySQL login password (Windows Environment)
How to use MySQL language for row and column devices?