gofmt 命令详解

| 选择喜欢的代码风格  

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z

gofmt 命令安装:


-bash: gofmt command not found

#Debian
apt-get install golang-1.12-go

#Ubuntu
apt-get install golang-1.12-go

#Arch Linux
pacman -S go-pie

#Kali Linux
apt-get install golang-1.11-go

#CentOS
yum install gcc-go

#Fedora
dnf install gcc-go

#Raspbian
apt-get install golang-1.6-go

gofmt 命令补充说明:


gofmt 命令格式化 Go 程序代码。它使用制表符进行缩进,并使用空格进行对齐。对齐方式假定编辑器使用的是固定宽度的字体。

如果没有明确的路径,它将处理标准输入。给定一个文件,它将对该文件进行操作;给定一个目录,它将以递归方式对该目录中的所有 .go 文件进行操作。(以句点开头的文件将被忽略。)默认情况下,gofmt 将重新格式化的源打印到标准输出。

gofmt 命令语法:


gofmt [flags] [path ...]

gofmt 命令选项:


#The flags are:

-d
  Do not print reformatted sources to standard output.
  If a file's formatting is different than gofmt's, print diffs
  to standard output.
-e
  Print all (including spurious) errors.
-l
  Do not print reformatted sources to standard output.
  If a file's formatting is different from gofmt's, print its name
  to standard output.
-r rule
  Apply the rewrite rule to the source before reformatting.
-s
  Try to simplify code (after applying the rewrite rule, if any).
-w
  Do not print reformatted sources to standard output.
  If a file's formatting is different from gofmt's, overwrite it
  with gofmt's version. If an error occurred during overwriting,
  the original file is restored from an automatic backup.


#Debugging support:

-cpuprofile filename
  Write cpu profile to the specified file.


#The rewrite rule specified with the -r flag must be a string of the form:

pattern -> replacement

gofmt 命令参数:


需要操作的目标 go 代码文件

gofmt 命令实例:


gofmt 格式化文件并将结果显示到控制台:

gofmt source.go

gofmt 格式化文件,就地覆盖原始文件:

gofmt -w source.go

gofmt 格式化文件,然后简化代码,覆盖原始文件:

gofmt -s -w source.go

gofmt 打印所有(包括伪造的)错误:

gofmt -e source.go

gofmt 命令扩展阅读:




gofmt 命令评论