当前位置:网站首页>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
边栏推荐
- 【Hot100】19. 删除链表的倒数第 N 个结点
- Five years after graduation, I became a test development engineer with an annual salary of 30w+
- ssm框架原理
- 搜索框和按钮缩放时会有缝隙的bug
- Guide for high-end programmers to fish at work
- The picgo shortcut is amazing. This person thinks exactly the same as me
- FPN网络详解
- ThinkPHP kernel work order system source code commercial open source version multi user + multi customer service + SMS + email notification
- 使用腾讯云搭建图床服务
- 接口测试框架中的鉴权处理
猜你喜欢

idea启动Command line is too long问题处理

Share the daily work and welfare of DJI (Shenzhen headquarters) in Dajiang

How to write good code - Defensive Programming Guide

Authentication processing in interface testing framework
![[SQL statement] Why do you select two Shanghai and query different counts here? I want it to become a Shanghai, and count only displays a sum](/img/a4/58b942d1389834069e9a6ec9f8ee0a.png)
[SQL statement] Why do you select two Shanghai and query different counts here? I want it to become a Shanghai, and count only displays a sum

In the past six months, it has been invested by five "giants", and this intelligent driving "dark horse" is sought after by capital

Comment utiliser le langage MySQL pour les appareils de ligne et de ligne?

process. env. NODE_ ENV

Go language learning notes - Gorm use - table addition, deletion, modification and query | web framework gin (VIII)

SQLServer查询: a.id与b.id相同时,a.id对应的a.p在b.id对应的b.p里找不到的话,就显示出这个a.id和a.p
随机推荐
vscode 查找 替换 一个文件夹下所有文件的数据
[PHP graduation design] design and implementation of textbook management system based on php+mysql+apache (graduation thesis + program source code) -- textbook management system
The Department came to a Post-00 test paper king who took out 25K. The veteran said it was really dry, but it had been
怎么用MySQL语言进行行列装置?
电脑照片尺寸如何调整成自己想要的
How to use phpipam to manage IP addresses and subnets
Task. Run(), Task. Factory. Analysis of behavior inconsistency between startnew() and new task()
Virtual serial port simulator and serial port debugging assistant tutorial "suggestions collection"
Go 语言怎么优化重复的 if err != nil 样板代码?
[SQL statement] Why do you select two Shanghai and query different counts here? I want it to become a Shanghai, and count only displays a sum
Huawei issued hcsp-solution-5g security talent certification to help build 5g security talent ecosystem
苹果自研基带芯片再次失败,说明了华为海思的技术领先性
Sweden announced its decision to exclude Huawei 5g equipment, but Huawei has successfully found a new way out
圈铁发音,动感与无噪强强出彩,魔浪HIFIair蓝牙耳机测评
FPN网络详解
The picgo shortcut is amazing. This person thinks exactly the same as me
如何使用phpIPAM来管理IP地址和子网
部门来了个拿25k出来的00后测试卷王,老油条表示真干不过,已被...
IM即時通訊開發實現心跳保活遇到的問題
数据库系统原理与应用教程(004)—— MySQL 安装与配置:重置 MySQL 登录密码(windows 环境)