当前位置:网站首页>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
边栏推荐
- 苹果自研基带芯片再次失败,说明了华为海思的技术领先性
- How does win11 set user permissions? Win11 method of setting user permissions
- 超视频时代,什么样的技术会成为底座?
- 芯片供应转向过剩,中国芯片日产增加至10亿,国外芯片将更难受
- How to use phpipam to manage IP addresses and subnets
- 运动捕捉系统原理
- Principes et applications du système de base de données (006) - - compilation et installation de MySQL 5.7 (environnement Linux)
- Action after deleting laravel's model
- 周少剑,很少见
- China's intelligent transportation construction from the perspective of "one hour life circle" in Dawan District
猜你喜欢
Research on multi model architecture of ads computing power chip
Talking from mlperf: how to lead the next wave of AI accelerator
Endeavouros mobile hard disk installation
process. env. NODE_ ENV
[nodemon] app crashed - waiting for file changes before starting...解决方法
Learn selenium to simulate mouse operation, and you can be lazy a little bit
瑞典公布决定排除华为5G设备,但是华为已成功找到新出路
分享在大疆DJI(深圳总部)工作的日常和福利
Motion capture system for apple picking robot
Do280 management application deployment - pod scheduling control
随机推荐
全面看待企业数字化转型的价值
程序员职业生涯真的很短吗?
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
Task. Run(), Task. Factory. Analysis of behavior inconsistency between startnew() and new task()
Zhou Shaojian, rare
picgo快捷键 绝了这人和我的想法 一模一样
芯片供应转向过剩,中国芯片日产增加至10亿,国外芯片将更难受
Comprehensively view the value of enterprise digital transformation
Microservice tracking SQL (support Gorm query tracking under isto control)
Introduction to RT thread env tool (learning notes)
苹果自研基带芯片再次失败,说明了华为海思的技术领先性
C#/VB. Net merge PDF document
Im instant messaging develops a message delivery scheme for 10000 people
Embedded development: five revision control best practices
Do280 management application deployment - pod scheduling control
MLPerf Training v2.0 榜单发布,在同等GPU配置下百度飞桨性能世界第一
怎么用MySQL语言进行行列装置?
Win11如何设置用户权限?Win11设置用户权限的方法
近半年内连获5家“巨头”投资,这家智能驾驶“黑马”受资本追捧
Tutorial on principles and applications of database system (004) -- MySQL installation and configuration: resetting MySQL login password (Windows Environment)