Let’s look directly at a piece of code
type MyselfError struct{} func (m *MyselfError) Error() string { return "实现 error 接口的 Error 方法" } func someWork() *MyselfError { return nil } func main() { var err error err = someWork() fmt.Println(err == nil) } // output: false
The output of this example might surprise you?
This is because in Go, the comparison of two nil may not be equal. In the article Comparability of Go Language Types we said: For interfaces, there are two dimensions for comparison, namely dynamic type and dynamic value. The <span style="font-size: 15px;">==</span>
comparison of the interface will be true only if the type and value are equal.
type error interface { Error() string }
<span style="font-size: 15px;">someWork</span>
The err returned by the function is an error interface of type MyselfError and value nil, which obviously does not meet the requirements: Only when the type and value are both nil, the nil judgment of the interface type will be true.
Main branch code
With the above foreshadowing, you should understand what I am going to say, right?
在 Go 中,不要通过<span style="font-size: 15px;">err == nil</span>
来做逻辑判断条件。这不光是由于使用它会产生潜在的 bug,这样的代码交于测试童鞋,他们可能也会喷你,你知道是为什么吗?
我们可以把代码分为主干代码和分支代码,主干代码代表正常逻辑,分支代码记录异常case。两者最简单的区分方法就是:在一个函数中,主干代码与最左侧只隔一个 tab 距离,超过一个 tab 距离的为分支代码。
在处理错误返回的函数中,我们应该先做错误异常的处理,错误处理的逻辑属于分支代码,而正常逻辑则应在主干代码上。
错误示例
func bar() { var err error err = foo() if err == nil { // 程序正常的代码逻辑 } else { switch err.(type) { case err1: // 做错误处理1 case err2: // 做错误处理2 default: // 做通用错误处理 } } }
现在你能知道测试童鞋为什么喷你吗?
有一个词叫做测试覆盖率,它代表测试用例走过的代码行数。如果你将<span style="font-size: 15px;">err==nil</span>
的判断前置,那这段代码就对于测试不友好。
在测试过程中,有时我们很难人为构造错误的发生,那么很可能测试用例只会走<span style="font-size: 15px;">err==nil</span>
下面的代码逻辑。
规范示例
func main() { var err error err = foo() if err != nil { switch err.(type) { case err1: // 做错误处理1 case err2: // 做错误处理2 default: // 做通用错误处理 } } // 程序正常的代码逻辑 }
这样的代码规范,让我们在初次接手新项目,或者 code review 其他人的代码时,能够通过阅读主干代码而快速理解地代码业务逻辑,而不至于陷入琐碎的 case 处理中。
总结
今天的文章虽然很短,但是希望能给大家带来启示。
在 Go 中 err == nil 不需要判断,而该判断异常 case,正常逻辑置于主干,异常代码置于分支。
Establishing a good set of coding standards within the development team will help improve code readability and work collaboration efficiency. If you don’t have similar specifications yet, then refer to Go Code Review Comments and uber-go/guide to make a complete set?
The above is the detailed content of Write some standard Go code. For more information, please follow other related articles on the PHP Chinese website!

Goimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:

C is more suitable for scenarios where direct control of hardware resources and high performance optimization is required, while Golang is more suitable for scenarios where rapid development and high concurrency processing are required. 1.C's advantage lies in its close to hardware characteristics and high optimization capabilities, which are suitable for high-performance needs such as game development. 2.Golang's advantage lies in its concise syntax and natural concurrency support, which is suitable for high concurrency service development.

Golang excels in practical applications and is known for its simplicity, efficiency and concurrency. 1) Concurrent programming is implemented through Goroutines and Channels, 2) Flexible code is written using interfaces and polymorphisms, 3) Simplify network programming with net/http packages, 4) Build efficient concurrent crawlers, 5) Debugging and optimizing through tools and best practices.

The core features of Go include garbage collection, static linking and concurrency support. 1. The concurrency model of Go language realizes efficient concurrent programming through goroutine and channel. 2. Interfaces and polymorphisms are implemented through interface methods, so that different types can be processed in a unified manner. 3. The basic usage demonstrates the efficiency of function definition and call. 4. In advanced usage, slices provide powerful functions of dynamic resizing. 5. Common errors such as race conditions can be detected and resolved through getest-race. 6. Performance optimization Reuse objects through sync.Pool to reduce garbage collection pressure.

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

Confused about the sorting of SQL query results. In the process of learning SQL, you often encounter some confusing problems. Recently, the author is reading "MICK-SQL Basics"...

The relationship between technology stack convergence and technology selection In software development, the selection and management of technology stacks are a very critical issue. Recently, some readers have proposed...

Golang ...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),