Golang具有一套可以构建和处理go源代码的程序,作为命令行工具,这些程序也并非直接运行,而是由go程序调用。运行这些程序最常见的方式是作为go程序的子命令,例如 go fmt,该命令的运行方式是由go程序使用适合于包级处理的参数调用底层二进制文件,对go源代码的完整包进行操作;这些程序也可以作为独立的二进制文件运行,使用go tool子命令(如go tool cgo)使用未修改的参数;某些命令(如pprof)只能通过go tool子命令访问。go命令行作为日常开发的工具,能大大方便编译、调试、诊断程序性能等工作,本文是对常见go命令行工具使用的汇总
go命令
go命令管理go源代码并运行此处列出的其他命令。在终端输入go,会打印出如下信息
$ go
Go is a tool for managing Go source code.
Usage:
go <command> [arguments]
The commands are:
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
Use "go help <command>" for more information about a command.
Additional help topics:
buildmode build modes
c calling between Go and C
cache build and test caching
environment environment variables
filetype file types
go.mod the go.mod file
gopath GOPATH environment variable
gopath-get legacy GOPATH go get
goproxy module proxy protocol
importpath import path syntax
modules modules, module versions, and more
module-get module-aware go get
module-auth module authentication using go.sum
module-private module configuration for non-public modules
packages package lists and patterns
testflag testing flags
testfunc testing functions
Use "go help <topic>" for more information about that to![]()pic.
下面介绍命令部分
启动错误报告 运行go bug
命令,Bug打开默认浏览器并启动新的Bug报告,报告包括有用的系统信息
编译包和依赖项 用法如下
go build [-o output] [-i] [build flags] [packages]
build编译由导入路径命名的包及其依赖项,但不安装编译结果。如果build的参数是来自单个目录的.go文件列表,则build会将它们视为指定单个包的源文件列表;编译包时,build将忽略以"_test.go"结尾的文件
在编译单个main包时,build将生成的可执行文件写入以第一个源文件(go build ed.go rx.go
输出的二进制文件名为 'ed' 或 'ed.exe')或源代码目录(go build unix/sam
输出的二进制文件名为 'sam' 或 'sam.exe')命名的输出文件(写入Windows可执行文件时会添加.exe
后缀);编译多个包或单个非main包时,build会编译包,但会丢弃生成的对象,仅用于检查包是否可编译
删除对象文件和缓存文件 用法如下
go clean [clean flags] [build flags] [packages]
clean从包源目录中删除对象文件。go命令在一个临时目录中构建大多数对象,因此go clean主要关注其他go工具或通过手动调用go build
留下的对象文件
展示包或符号的文档 用法
go doc [-u] [-c] [package|[package.]symbol[.methodOrField]]
go doc <pkg>
go doc <sym>[.<methodOrField>]
go doc [<pkg>.]<sym>[.<methodOrField>]
go doc [<pkg>.][<sym>.]<methodOrField>
// 在所有形式中,当匹配符号时,参数中的小写字母与任意一个大写字母都匹配,
// 但大写字母完全匹配。这意味着,如果不同的符号有不同的大小写,则包中的小写参数可能有多个匹配项。如果出现这种情况,则打印所有匹配的文档
## 例子
go doc 展示当前包的文档
go doc Foo 展示当前包中Foo的文档(Foo为首字母大写,因此不会匹配包路径)