使用 gofmt 格式化源码
gofmt 工具是 Go 语言自带的源码格式化工具,它可以帮助我们格式化代码,让代码风格保持一致。
Terminal
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
使用 -s 简化代码
-s 参数可以简化代码,它可以做一些代码优化,例如:
// 存在一个字符串切片 v:
v := []string{...}
// 如果只关心迭代次数,可以这样写:
for _ := range v {
...
}
// 也可以简化为:
for range v {
...
}
更推荐后面的的简化后的写法。为了避免将代码转换为简化语法带来的额外工作,我们可以使用gofmt -s
,而且没有副作用。
使用 goimports 自动添加包
goimports 是一个由 Go 团队开发的工具,它可以帮助我们自动添加或删除 import 包,它的使用方法和 gofmt 工具类似:
安装方法:
go install golang.org/x/tools/cmd/goimports@latest
使用方法:
Terminal
./goimports -help
usage: goimports [flags] [path ...]
-cpuprofile string
CPU profile output
-d display diffs instead of rewriting files
-e report all errors (not just the first 10 on different lines)
-format-only
if true, don't fix imports and only format. In this mode, goimports is effectively gofmt, with the addition that imports are grouped into sections.
-l list files whose formatting differs from goimport's
-local string
put imports beginning with this string after 3rd-party packages; comma-separated list
-memprofile string
memory profile output
-memrate int
if > 0, sets runtime.MemProfileRate
-srcdir dir
choose imports as if source code is from dir. When operating on a single file, dir may instead be the complete file name.
-trace string
trace profile output
-v verbose logging
-w write result to (source) file instead of stdout
VScode 集成
进入扩展商店,搜索 go,安装 Go 插件,安装完成后,按照提示继续安装所依赖的第三方工具。