Detailed explanation of Go language code line breaking rules

This article takes an in-depth look at all aspects of code line breaking in Go, from basic concepts to practical application practices.

Follow [TechLeadCloud] to share full-dimensional knowledge of Internet architecture and cloud service technology. The author has 10+ years of Internet service architecture, AI product development experience, and team management experience. He holds a master's degree from Tongji University in Fudan University, a member of Fudan Robot Intelligence Laboratory, a senior architect certified by Alibaba Cloud, a project management professional, and research and development of AI products with revenue of hundreds of millions. principal.

file

1. The concept of line breaks in Go code

Code line breaks, or code wraps, are a common but often overlooked detail in programming. It involves how to add a newline character at the end of a line of code so that the code is displayed as a multi-line structure. Code line breaks not only affect the readability and aesthetics of the code, but may also be related to the syntax of the programming language, compiler behavior, and tool chain interaction. In the Go language, this concept is especially important because of Go's unique line breaking rules and tool support.

Why do you need line breaks in code?

readability

The first purpose of code line breaking is to improve the readability of the code. Long lines of code can be difficult to read at a glance, especially when the code is logically complex or involves multiple operators.

Example

// 不佳的代码断行
if x > 0 && y > 0 && z > 0 && a > 0 && b > 0 { doSomething() }

// 优雅的代码断行
if x > 0 &&
   y > 0 &&
   z > 0 &&
   a > 0 &&
   b > 0 {
  doSomething()
}

Output: Make complex conditional statements easier to understand by breaking lines.

Grammar requirements

Some programming languages ​​have strict code line breaking rules. The line breaking rules in the Go language are relatively loose, but some specific scenarios (for example, using ,instead at the end of a line ;) still have clear requirements.

Example

// 错误示例:Go不允许在声明中的最后一个字段后添加逗号
var x = []int{1, 2, 3,}

// 正确示例
var x = []int{1, 2, 3}

Output: Note that there should be no comma after the last element in an array or slice declaration in Go.

Line breaking tool in Go language

gofmt

Go provides a gofmttool called , which is used to automatically format code, including code line breaks.

Example

Original code:

func foo(x,y int)int{return x+y}

After running gofmt:

func foo(x, y int) int { return x + y }

Output: gofmtCode line breaks and spaces are automatically added to make the code more readable.

goimports

goimportsis another tool for automatically formatting Go code. It gofmtadds the function of automatically processing import statements based on.

Example

Original code:

package main
func main() { fmt.Println("Hello, world!") }

After running goimports:

package main

import "fmt"

func main() { fmt.Println("Hello, world!") }

Output: goimportsMissing importdeclarations automatically added and code line breaks made.

Here we introduce in detail some basic concepts of Go code line breaks, why it is needed, and how Go-specific tools can help us better handle code line breaks. This lays a solid foundation for us to further explore more details and application scenarios of Go code line breaking.


2. Go code line breaking practice

After understanding the basic concepts of line breaking in Go code, let's take a look at how to apply these rules and tools in actual programming practice. Here we will discuss line breaking practices in different scenarios, IDEs and line breaking, and how to unify line breaking rules in projects.

Line breaking practice in different scenarios

Function declaration and calling

In function declarations and calls, line breaks are often required to improve code readability when there are too many parameters.

Example

// 不佳的函数声明
func add(x, y, z, a, b, c int, s1, s2, s3 string) int {
  return x + y + z + a + b + c
}

// 优雅的函数声明
func add(
  x, y, z int,
  a, b, c int,
  s1, s2, s3 string,
) int {
  return x + y + z + a + b + c
}

Output: Use line breaks to clearly arrange multiple parameters.

Structures and interfaces

Structure and interface declarations in Go language also need to pay attention to line breaks.

Example

// 不佳的结构体声明
type Person struct{FirstName, LastName string; Age int}

// 优雅的结构体声明
type Person struct {
  FirstName string
  LastName  string
  Age       int
}

Output: Use breaks to make structure fields easier to see.

flow control statement

When flow control statements such as if, for, switchetc. involve multiple conditions or complex expressions, line breaks can bring better readability.

Example

// 不佳的if语句
if x>0 && y>0 || z==0 && a!=0 { doSomething() }

// 优雅的if语句
if (x > 0 && y > 0) ||
   (z == 0 && a != 0) {
  doSomething()
}

Output: Make complex if conditions easier to interpret with appropriate line breaks.

IDE decision-making

automatic formatting

Most modern IDEs support automatic formatting of the Go language, including automatic line breaking.

Example

In VS Code, you can automatically run gofmtor goimports.

Output: With the IDE's auto-formatting feature, you can easily follow Go's line breaking rules.

shortcut key

Use the shortcut keys provided by the IDE to quickly break code lines.

Example

In IntelliJ IDEA or GoLand, you can use Alt+Entershortcut keys to quickly break lines.

Output: Through shortcut keys, we can break lines very conveniently while writing code.

Unify line breaking rules across projects

Configuration file

Line breaking rules can be unified across your team by sharing configuration files such as .editorconfig.go.project

Example

.editorconfigAdd the following rules to the file:

[*.{go}]
indent_style = space
indent_size = 2

Output: This way, team members' IDEs will automatically adopt these line breaking and indentation rules.

CI/CD integration

gofmtBy integrating OR in the CI/CD process goimports, you can ensure that all code in the project follows uniform line breaking rules.

Example

Configure in GitHub Actions:

jobs:
  gofmt:
    runs-on: ubuntu-latest
    steps:
      - name: Check out code
        uses: actions/checkout@v2

      - name: Run gofmt
        run: test -z $(gofmt -l .)

Output: If any code is not gofmtformatted according to the rules, the CI/CD process will fail.

In this section, we discuss in depth how to apply line breaking rules and tools in actual Go programming practice, including best practices in different coding scenarios, and how to unify line breaking rules at the IDE and project levels. Hopefully this content will help you use line breaks more effectively in Go programming, thereby improving code quality and maintainability.

Follow [TechLeadCloud] to share full-dimensional knowledge of Internet architecture and cloud service technology. The author has 10+ years of Internet service architecture, AI product development experience, and team management experience. He holds a master's degree from Tongji University in Fudan University, a member of Fudan Robot Intelligence Laboratory, a senior architect certified by Alibaba Cloud, a project management professional, and research and development of AI products with revenue of hundreds of millions. principal. If it helps, please pay more attention to TeahLead KrisChang, 10+ years of experience in the Internet and artificial intelligence industry, 10+ years of experience in technical and business team management, bachelor's degree in software engineering from Tongji, master's degree in engineering management from Fudan, Alibaba Cloud certified senior architect of cloud services, Head of AI product business with revenue of over 100 million.

Microsoft launches new "Windows App" .NET 8 officially GA, the latest LTS version Xiaomi officially announced that Xiaomi Vela is fully open source, and the underlying kernel is NuttX Alibaba Cloud 11.12 The cause of the failure is exposed: Access Key Service (Access Key) exception Vite 5 officially released GitHub report : TypeScript replaces Java and becomes the third most popular language Offering a reward of hundreds of thousands of dollars to rewrite Prettier in Rust Asking the open source author "Is the project still alive?" Very rude and disrespectful Bytedance: Using AI to automatically tune Linux kernel parameter operators Magic operation: disconnect the network in the background, deactivate the broadband account, and force the user to change the optical modem
{{o.name}}
{{m.name}}

Guess you like

Origin my.oschina.net/u/6723965/blog/10122433