Go从入门到精通——代码格式化工具 gofmt

代码格式化工具 gofmt

  Go 语言中的格式要求如此严格,是否会给开发者带来很多麻烦呢?Go 语言的设计团队显然已经考虑到了这个为,因此提供了相应的工具来帮助开发者避免大部分重复性的格式上的工作。这个工具就是 gofmt,在安装完 Go 语言安装包之后可以直接通过命令行运行 gofmt 软件进行代码的自动格式化。

package main

import ("fmt")

func main() {
	a:=1
	if (a >= 1) {fmt.Println((a))}
}

  我发现不管是 vscode、gofmt 都可以格式化该代码问题。gofmt 执行命令为:

gofmt xxx.go       #对代码进行格式优化后输出结果
gofmt -w xxx.go  #直接优化后保存到原来的代码文件 xxx.go 中

  代码中问题如下:

    • import 语句中一般将括号分为两行并且其中每个导包占一行。
    • a:=1 这一语句中,":=" 操作符前后应有空格。
    • if 开始的条件判断句中的单个条件不需要加上圆括号,并且后面的条件分支语句也应换行。

  另外,也可以直接在 包 目录下执行 go fmt 命令,将该包中的代码全部进行格式化优化。

  Go 语言中,类似 gofmt 这类工具(包括 Go 语言主程序 go 本身)都可以加上 --help 命令行参数来获取帮助信息,类似 gofmt -h 将输出下面的类似信息:

D:go-testfiles>gofmt -h
usage: gofmt [flags] [path ...]
  -cpuprofile string
        write cpu profile to this file
  -d    display diffs instead of rewriting files
  -e    report all errors (not just the first 10 on different lines)
  -l    list files whose formatting differs from gofmt's
  -r string
        rewrite rule (e.g., 'a[b:len(a)] -> a[b:]')
  -s    simplify code
  -w    write result to (source) file instead of stdout

D:go-testfiles>
原文地址:https://www.cnblogs.com/zuoyang/p/15206396.html