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!

Go's strings package provides a variety of string manipulation functions. 1) Use strings.Contains to check substrings. 2) Use strings.Split to split the string into substring slices. 3) Merge strings through strings.Join. 4) Use strings.TrimSpace or strings.Trim to remove blanks or specified characters at the beginning and end of a string. 5) Replace all specified substrings with strings.ReplaceAll. 6) Use strings.HasPrefix or strings.HasSuffix to check the prefix or suffix of the string.

Using the Go language strings package can improve code quality. 1) Use strings.Join() to elegantly connect string arrays to avoid performance overhead. 2) Combine strings.Split() and strings.Contains() to process text and pay attention to case sensitivity issues. 3) Avoid abuse of strings.Replace() and consider using regular expressions for a large number of substitutions. 4) Use strings.Builder to improve the performance of frequently splicing strings.

Go's bytes package provides a variety of practical functions to handle byte slicing. 1.bytes.Contains is used to check whether the byte slice contains a specific sequence. 2.bytes.Split is used to split byte slices into smallerpieces. 3.bytes.Join is used to concatenate multiple byte slices into one. 4.bytes.TrimSpace is used to remove the front and back blanks of byte slices. 5.bytes.Equal is used to compare whether two byte slices are equal. 6.bytes.Index is used to find the starting index of sub-slices in largerslices.

Theencoding/binarypackageinGoisessentialbecauseitprovidesastandardizedwaytoreadandwritebinarydata,ensuringcross-platformcompatibilityandhandlingdifferentendianness.ItoffersfunctionslikeRead,Write,ReadUvarint,andWriteUvarintforprecisecontroloverbinary

ThebytespackageinGoiscrucialforhandlingbyteslicesandbuffers,offeringtoolsforefficientmemorymanagementanddatamanipulation.1)Itprovidesfunctionalitieslikecreatingbuffers,comparingslices,andsearching/replacingwithinslices.2)Forlargedatasets,usingbytes.N

You should care about the "strings" package in Go because it provides tools for handling text data, splicing from basic strings to advanced regular expression matching. 1) The "strings" package provides efficient string operations, such as Join functions used to splice strings to avoid performance problems. 2) It contains advanced functions, such as the ContainsAny function, to check whether a string contains a specific character set. 3) The Replace function is used to replace substrings in a string, and attention should be paid to the replacement order and case sensitivity. 4) The Split function can split strings according to the separator and is often used for regular expression processing. 5) Performance needs to be considered when using, such as

The"encoding/binary"packageinGoisessentialforhandlingbinarydata,offeringtoolsforreadingandwritingbinarydataefficiently.1)Itsupportsbothlittle-endianandbig-endianbyteorders,crucialforcross-systemcompatibility.2)Thepackageallowsworkingwithcus

Mastering the bytes package in Go can help improve the efficiency and elegance of your code. 1) The bytes package is crucial for parsing binary data, processing network protocols, and memory management. 2) Use bytes.Buffer to gradually build byte slices. 3) The bytes package provides the functions of searching, replacing and segmenting byte slices. 4) The bytes.Reader type is suitable for reading data from byte slices, especially in I/O operations. 5) The bytes package works in collaboration with Go's garbage collector, improving the efficiency of big data processing.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6
Visual web development tools

Atom editor mac version download
The most popular open source editor
