Table of Contents
Main branch code" >Main branch code
错误示例
规范示例
总结" >总结
Home Backend Development Golang Write some standard Go code

Write some standard Go code

Jul 24, 2023 pm 02:43 PM
go go language

Enlightenment Code

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
Copy after login

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
}
Copy after login

<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:
   // 做通用错误处理
  }
 }
}
Copy after login

现在你能知道测试童鞋为什么喷你吗?

有一个词叫做测试覆盖率,它代表测试用例走过的代码行数。如果你将<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:
   // 做通用错误处理
  }
 }
 // 程序正常的代码逻辑
}
Copy after login

这样的代码规范,让我们在初次接手新项目,或者 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

What is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

Why is it necessary to pass pointers when using Go and viper libraries? Why is it necessary to pass pointers when using Go and viper libraries? Apr 02, 2025 pm 04:00 PM

Go pointer syntax and addressing problems in the use of viper library When programming in Go language, it is crucial to understand the syntax and usage of pointers, especially in...

See all articles