Home > Backend Development > Golang > Does Go language have indentation?

Does Go language have indentation?

青灯夜游
Release: 2022-12-01 18:54:57
Original
6590 people have browsed it

Go language has indentation. In the Go language, indentation can be formatted directly using the gofmt tool (gofmt uses tabs for indentation); the gofmt tool will format the source code with standard style indentation and vertical alignment, and even comments if necessary. will be reformatted.

Does Go language have indentation?

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

Go language code style

(1) Indentation and line breaks

Indentation Just use the gofmt tool to format directly (gofmt uses tab indentation). gofmt is a tool that formats source code with standard styles of indentation and vertical alignment, and even comments are reformatted if necessary.

In terms of line breaks, the maximum length of a line should not exceed 120 characters. If it exceeds, please use line breaks to display and try to keep the format elegant

We use the GoLand development tool and directly use the shortcut key: Ctrl Alt L That’s it.

(2) The end of the statement

In Go language, there is no need to end with a semicolon similar to Java. By default, one line is one piece of data.

If you plan to write multiple statements on the same line, they must be used.

(3) Brackets and spaces

In terms of brackets and spaces, you can also directly use the gofmt tool to format (go will force the left brace not to wrap, and the newline will report syntax error), leave spaces between all operators and operands.

//正确的方式
if a > 0 {

}
//错误的方式
if a>0  // a,>,0之间应该使用空格
{       //左大括号不可以换行,会报语法错误
	
}
Copy after login

(4) Import specifications

In the case of multiple lines of import, goimports will automatically format it for you. If you introduce a package into a file , it is recommended to use the following format:

import {
	"fmt"
}
Copy after login

If your package introduces three types of packages, standard library packages, program internal packages, and third-party packages, it is recommended to organize your package in the following way

inport{
	"encoding/json"
	"strings"
	
	"myproject/models"
	"myproject/controller"
	
	"github.com/astaxie/beego"
}
Copy after login

Introduce packages in order. Different types are separated by spaces. The first is the actual quasi-library, the second is the project package, and the third is the third-party package. [Related recommendations: Go video tutorial]

Do not use relative paths to introduce packages in the project

(5) Error handling

The principle of error handling is that you cannot discard any call that returns err. Do not use _discard, all must be processed. When receiving an error, either return err, or use log to record it

  • Return as soon as possible: Once an error occurs, return immediately

  • Try not to use it panic, unless you know what you are doing

  • The error description must be in lowercase if it is in English, no punctuation is required at the end

  • Use an independent error Stream processing

// 错误写法
if err != nil {
	// error handing
} else {
	//normal code
}

// 正确写法
if err != nil {
	// error handing
	return // or continue, etc.
}
//  normal code
Copy after login

(6) Test

The unit test file naming convention is example_test.go

test case Function names must start with Test

Every important function must first write a test case, and submit the test case together with the regular code to facilitate regression testing

Go language gofmt command

gofmt is a single command used to format Go source code. It uses tabs for indentation and spaces for alignment. Alignment assumes the editor is using a fixed-width font. If no path is explicitly specified, it will process standard input; given a file, it will process that file; given a folder, it will recursively process all .go files under the folder (except hidden files). By default, gofmt will print the reformatted code to standard output (rather than updating the source file directly).

Usage is as follows:

gofmt [flags] [path ...]
Copy after login

flags are as follows:

  • -d The reformatted code will no longer be printed to the standard output. If the file code format is inconsistent with gofmt, print the difference to the standard output (this flag is similar to the git diff command).

  • -e Print all errors (including false ones).

  • -l The reformatted code is no longer printed to standard output. If the file code format is inconsistent with gofmt, print the file name to standard output.

  • -r rule Apply the specified rewrite rule before reformatting the source file.

  • -s After applying the rules (if any), try to simplify the code.

  • -w The reformatted code is no longer printed to standard output. If the file code format is inconsistent with gofmt, use the gofmt version for rewriting. If an error occurs during the rewriting process, the original files will be restored using automatic backup.

Debugging support:

  • -cpuprofile filename Write cpuprofile to the specified file.

Note: The rewriting rule specified by the -r flag must be in the form of a string: pattern -> replacement

pattern and replacement parts Must be a valid Go expression. In pattern, single-character lowercase identifiers are used as wildcards to match any subexpressions that will be replaced by the same identifier in replacement.

当gofmt从标准输入读取时,即接受一个完整的Go程序,也可以是一个程序片段。程序片段必须是语法上有效的声明列表,语句列表或表达式。格式化这种片段时,gofmt会保留前导缩进和前后的空格,以便Go程序的各个部分可以通过gofmt来格式化。

示例

假设源文件(hello.go)内容如下:

package main

import "fmt"

func main() {

    x := 2
y := 3// 该行未对齐

    str := "Hello Golang~"
    var greeting string

    greeting = (str)// 本行含有不必要的括号

    fmt.Println(greeting)
    fmt.Println("x*y =", ((x) * y))// 本行含有不必要的括号

    s := []int{1, 3, 5, 6, 7}// 切片

    start := 2

    sub := s[start:len(s)]// 本行可以优化切片s上界

    fmt.Println(s)
    fmt.Println(sub)
}
Copy after login

1.检查文件中不必要的括号(如果有,则输出文件名):

gofmt -r '(a) -> a' -l *.go
Copy after login

将会输出hello.go

2.移除括号:

gofmt -r '(a) -> a' -w *.go
Copy after login

源文件将变成如下格式:

package main

import "fmt"

func main() {

    x := 2
    y := 3 // 该行未对齐

    str := "Hello Golang~"
    var greeting string

    greeting = str // 本行含有不必要的括号

    fmt.Println(greeting)
    fmt.Println("x*y =", x*y) // 本行含有不必要的括号

    s := []int{1, 3, 5, 6, 7} // 切片

    start := 2

    sub := s[start:len(s)] // 本行可以优化切片s上界

    fmt.Println(s)
    fmt.Println(sub)
}
Copy after login

注意看带注释的行发生的变化。

3.当前目录下,从显式切片上界转换为隐式切片上界:

gofmt -r 'α[β:len(α)] -> α[β:]' -w ./
Copy after login

源文件第22行将变成如下:

    sub := s[start:] // 本行可以优化切片上限
Copy after login

代码简化

使用-s调用gofmt时,将尽可能进行以下转换:

以下数组,切片或映射的复合字面量形式:

    []T{T{}, T{}}
Copy after login

将被简化为:

    []T{{}, {}}
Copy after login

以下切片表达式形式:

    s[a:len(s)]
Copy after login

将被简化为:

    s[a:]
Copy after login

以下range形式:

    for x, _ = range v {...}
Copy after login

将被简化为:

    for x = range v {...}
Copy after login

以下range形式:

    for _ = range v {...}
Copy after login

将被简化为:

    for range v {...}
Copy after login

注意:这些改变可能与早期版本的Go不兼容。另外,官方文档中指出:

  • -r标识性能有点慢;

  • -w如果失败,还原后的源文件可能会丢失某些文件属性。

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of Does Go language have indentation?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template