Home >Backend Development >Golang >What is the function of go fmt command

What is the function of go fmt command

青灯夜游
青灯夜游Original
2023-01-28 11:42:371821browse

In the go language, the "go fmt" command is mainly used to help developers format the code files they have written. The "go fmt" command will format the code of all Go language source code files in the specified code package according to the Go language code specifications. All Go language source code files include command source code files, library source code files and test source code files. The "go fmt" command will only format Go language source code files that are directly saved in the directory corresponding to the specified code package.

What is the function of go fmt command

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

go fmt command introduction

For a programming language, code formatting is the most controversial issue. Different Developers may have different coding styles and habits, but if all developers can write code in the same format, developers can focus on the problem the language is trying to solve, saving development time.

The Go language development team has formulated a unified official code style and launched the gofmt tool (gofmt or go fmt) to help developers format their code into a unified style.

gofmt is a cli program that will read standard input first. If a file path is passed in, the file will be formatted. If a directory is passed in, all .go files in the directory will be formatted. If If no parameters are passed, all .go files in the current directory will be formatted.

There is also a go fmt command in the Go language. The go fmt command is a simple encapsulation of gofmt.

What is the function of go fmt command

The go fmt command is mainly used to help you format the code files you have written [Many third-party integration software uses go fmt Command】

Usage:

go fmt <文件名>.go

Use go fmt command, more often gofmt is used, and the parameter -w is required, otherwise the formatting result will not be written to the file . gofmt -w src, you can format the entire project.

Parameter introduction

  • -l Display the files that need to be formatted

  • -w Put The rewritten content is written directly to the file instead of being printed to standard output as the result.

  • -r Add a rewrite rule in the form of "a[b:len(a)] -> a[b:]" to facilitate batch replacement

  • -s Simplify the code in the file

  • -d Display the diff before and after formatting instead of writing to the file, the default is false

  • -e Print all syntax errors to standard output. If you don't use this tag, only the first 10 errors on different lines will be printed.

  • -cpuprofile supports debugging mode and writes the corresponding cpufile to the specified file scope

go fmt and gofmt

The go fmt command will format the codes of all Go language source code files in the specified code package according to the Go language code specifications. All Go language source code files include command source code files and library source codes. files and test source code files. Note that when the code package also has sub-code packages, the Go language source code files in the sub-code packages are not included. In other words, the go fmt command will only format Go language source code files that are directly saved in the directory corresponding to the specified code package.

Similar to the relationship between go doc command and godoc command, go fmt command is a simple encapsulation of gofmt command. The go fmt command itself can accept two tags. The -n flag allows the command program to just print out the internally used gofmt command and its flags and arguments without actually executing it. The -x flag will cause the command program to both print and execute the command. Inside the go fmt command program, the markers -l and -w will be added after the gofmt command it calls, and the paths of all Go language source files in the specified code package will be used as parameters, like this:

hc@ubt:~$ go fmt -n pkgtool
gofmt -l -w golang/goc2p/src/pkgtool/envir.go golang/goc2p/src pkgtoolenvir_test.go golang/goc2p/src/pkgtool/fpath.go golang/goc2p/src/pkgtool ipath.go golang/goc2p/src/pkgtool/pnode.go golang/goc2p/src/pkgtool/util.go golang/goc2p/src/pkgtool/util_test.go

Note that the path to the Go language source file as a parameter of the gofmt command is relative, not absolute. But this is just to make the parameters look shorter. Therefore, when we directly execute the gofmt command, there is no problem in using the absolute path of the source code file as a parameter. In fact, the relative path or absolute path of any Go source code file or directory containing Go language source code files can be used as parameters of the gofmt command. When using the absolute path or relative path of a directory containing Go language source code files as a parameter, the gofmt command will use the Go language source code files in this directory as the target source code file.

The tags added inside the go fmt command program when executing the gofmt command are fixed. If we want to use a different set of tags, we must use the gofmt command directly. Now let's take a look at all the tags accepted by the gofmt command. As shown in the table below.

Table 0-13 Mark description of gofmt command

##-cpuprofilePut CPU The summary is written to the specified file. The path to the file should be used as the value of this tag. -dShows the differences (if any) before and after formatting, rather than formatting those codes directly. -eReport all errors in the target source code file. By default, only the first 10 errors are displayed. -lOnly print the absolute paths of source code files that do not meet the formatting specifications and need to be rewritten by the command program to the standard output. Instead of printing all the rewritten content to standard output. -rAdd a rewrite rule in the form "a[b:len(a)] -> a[b:]". We need to use it if we need to customize some additional formatting rules. The rule string should be used as the value of this tag. -sSimplify the code in the file. -wWrite the rewritten content directly to the file instead of printing the result to the standard output.

After reading the information in the above table, we can easily understand the behavior of the go fmt command. Because it executes the gofmt command internally and adds the -l and -w flags. This will cause the command program to print the absolute path to the file that needs to be rewritten to standard output, and write the formatted content directly to the original file. By default, the gofmt command will print the formatted content directly to the standard output.

Actually, the command program will parse the contents of the target source code file into an abstract syntax tree. When a syntax error is found during the parsing process, the command program will display an error message and exit. By default, all syntax errors in the target source code file will not be displayed. We can add the -e flag to cause the command program to print all errors to the standard output.

Customized rewriting operation

By default, the rewriting operation of the Go language source code file by the gofmt command includes the following aspects:

  • Sort the order of code package import paths in the dependent package import statement block in lexicographic order.

  • Standardize indentation, spaces, and newlines between individual languages ​​or blocks of statements. For example, convert all \r\n to \n.

  • Small corrections to code syntax. For example, eliminate redundant parentheses in switch statement blocks used to determine variable types.

If you want to customize additional rewriting operations, you need to use the -r flag. The value of the -r flag must contain "->", such as a[b:len(a)] -> a[b:]. The left side of "->" should be an example of the expression that needs to be replaced, and the right side should be an example of the expression used to replace the expression on the left side of "->".

If we use the flag -r, the command program will parse the replaced expression and replacement expression in this flag value into expression nodes of the abstract syntax tree before parsing the source code file. If the parsing is unsuccessful, it means that subsequent replacement operations cannot be performed, and the command program will exit after printing an error message. If the parsing is successful, the command program will perform the expression replacement operation after successfully parsing the source code file. The command program will find the node in the abstract syntax tree of the source code file that matches the replaced expression and replace it with the replacement expression. The gofmt command supports but is not limited to the following custom replacement operations:

  • Replacement of program entity names. Program entities include variables, constants, functions, structures, and interfaces. For example: -r=array1->array2 and -r=FuncA->FuncB.

  • Replacement of program entity types, which also includes replacement of function parameters and result types. For example: -r=string->bool and -r=interface{}->int.

  • Removal of redundant parentheses. For example: if we set the mark -r=(x)->x like this, a = (-x.s) in the target code will be rewritten as a = -x.s, and it will also make ((b = -x.f()) in the code )) is rewritten as b = -x.f(), which will also cause c = -(x).f to be rewritten as c = -x.f, but d = (&x).s and e = (-x).f will not be removed. parentheses in (). In other words, the command program will remove redundant parentheses from the code without changing the semantics and creating grammatical ambiguity.

  • Replacement of numerical operations. For example: If we set the flag -r=x x->x*2 like this, all x x in the code will be replaced by x * 2. Moreover, if the expression to be replaced contains comments, these comments will be removed during the replacement operation. For example, with the same tag settings x /* It's comment */ x will still be replaced by x * 2.

  • Function call replacement based on parameter list. For example: if we set the flag -r='funcA(a)->FuncA(a, c)' like this, then the statement in the target code that calls function funcA and takes a variable as a parameter will be replaced by calling function FuncA with A statement with variable a and variable c as parameters. Note that a as a parameter in the replaced expression only indicates that the function funcA has a parameter, and does not care what the name of the parameter is. That is to say, with the same flag settings, funcA(b) or funcA(x) in the target code will be replaced by FuncA(a, c). Or, if we set the flag -r='funB(x...)->FunC(x)' like this, then funB(x...) or funB(y...) or other Similar calling functions will be replaced by FunC(x). Among them, when a parameter of type array/slice is followed by three English half-width periods "...", it indicates that each element in this parameter needs to be passed into the function as a separate parameter. Therefore, this replacement method can be used to batch follow up and correct the code that calls the function after the function name and/or parameter list is changed.

Code Simplification Operation

When we add the flag -s when executing the gofmt command, the command program will search for the target source code file. Simplify the code and simplify it. Simplifications include:

  • Eliminate unnecessary type declarations in array/slice initialization.

  • Eliminate unnecessary type declarations in dictionary initialization.

  • Eliminate unnecessary index specification during array/slice slicing operations.

  • 消除迭代时的非必要临时变量赋值操作。

这些操作基本上都是出于尽量使用Go语言的语法糖已达到减少代码量的目的。我们在编写Go语言代码的时候应该直接使用这些语法糖而不应该依赖使用gofmt命令来简化。这里所说的Go语言的语法糖,我们在第3章中已经有所介绍。

我们在本小节中详细介绍了go fmt命令和gofmt命令。下面我们再汇总一下这两个命令可以为我们做的事情。如下表。

表0-14 go fmt命令和gofmt命令的功能

Tag name Tag description
功能 go fmt命令 gofmt命令
格式化代码
列出不规范的源码文件
自动改写源码文件
显示对比信息 ×
提示全部错误 ×
简化代码 ×
自定义替换/重构辅助 ×
CPU概要记录 ×

最后,值得一提的是,当我们执行gofmt命令且没有加任何参数的时候,该命令将会进入到交互模式。在这种模式下,我们可以直接在命令行界面中输入源码,并以Ctrl-d结束。在Linux操作系统下,Ctrl-d代表EOF(End Of File,中文译为文件结束符)。需要注意的是,如果在一行的中间按下Ctrl-d,则表示输出“标准输入”的缓存区,所以这时必须连续按两次Ctrl-d。另外,在Windows操作系统下,Ctrl-z代表EOF,所以需要以Ctrl-z结束。在这之后,gofmt命令会像从源码文件中读取源码那样从命令行界面(也称为标准输入)读取源码,并在格式化后将结果打印到命令行界面(也称为标准输出)中。示例如下:

hc@ubt:~$ gofmt -r=&#39;fmt.Println(a)->fmt.Printf("%s\n", a)&#39;
if a=="print" {fmt.Println(a)}                            <----- 在此行的末尾键入回车和Ctrl-d。
warning: rewrite ignored for incomplete programs          <----- 此行及以下就是命令输出的内容。
if a == "print" {
        fmt.Println(a)
}

由上述示例可知,我们可以使用gofmt命令的交互模式格式化任意的代码片段。虽然会显示一行警告信息,但是格式化后的结果仍然会被打印出来。并且,在交互模式下,当我们输入的代码片段不符合Go语言的语法规则时,命令程序也会打印出错误提示信息。在其它方面,命令程序在交互模式与普通模式下的行为也是基本一致的。

【相关推荐:Go视频教程编程教学

The above is the detailed content of What is the function of go fmt command. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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