Go语言提供了一系列强大的工具,灵活使用这些工具,能够让我们的项目开发更加容易,工具集包含如下。
bug start a bug report
build compile packages and dependencies
clean remove object files and cached files
doc show documentation for package or symbol
env print Go environment information
fix update packages to use new APIs
fmt gofmt (reformat) package sources
generate generate Go files by processing source
get add dependencies to current module and install them
install compile and install packages and dependencies
list list packages or modules
mod module maintenance
run compile and run Go program
test test packages
tool run specified go tool
version print Go version
vet report likely mistakes in packages
工具的源码位于$GOPATH/src/cmd/internal,本篇文章主要讨论Go工具generate。
go语言自动化工具
go generate常用于自动生成代码,它可以在代码编译之前根据源代码生成代码。当运行go generate时,它将扫描与当前包相关的源代码文件,找出所有包含"// go:generate"的注释语句,提取并执行该注释后的命令,命令为可执行程序。该过程类似于调用执行shell脚本。
使用方法
- 添加特殊注释
//go:generate command argument...
- 执行generate命令
$ go generate [-run regexp] [-n] [-v] [-x] [build flags]