https://pkg.go.dev/cmd/go

https://pkg.go.dev/cmd/go#hdr-The_go_mod_file

go build

格式:go build [-o output] [build flags] [packages]

常用参数(build flags):

  • -C 在执行命令前切换目录
  • -gcflags [[pattern=]arg list] 传递给 go tool 的编译参数
  • -ldflags '[pattern=]arg list' 传递给 linker 的参数
  • -tags tag,list,分隔的 tag,可用于条件编译

go run

格式:go run [build flags] [-exec xprog] package [arguments…]

编译并运行 package main,通常的用法为:

go run . # 当前目录为 package main 所在
go run somewhere/cmd

go work

格式:go work <command> [arguments]

可选的 command 有:

command meaning
edit edit go.work from tools or scripts
init initialize workspace file
sync sync workspace build list to modules
use add modules to workspace file

go get

https://go.dev/ref/mod#go-get

用于添加、升级/降级或移除特定模块的依赖

格式:go get [-d] [-t] [-u] [build flags] [packages]

# Upgrade a specific module.
$ go get golang.org/x/net

# Upgrade modules that provide packages imported by packages in the main module.
$ go get -u ./...

# Upgrade or downgrade to a specific version of a module.
$ go get golang.org/x/text@v0.3.2

# Update to the commit on the module's master branch.
$ go get golang.org/x/text@master

# Remove a dependency on a module and downgrade modules that require it
# to versions that don't require it.
$ go get golang.org/x/text@none

# Upgrade the minimum required Go version for the main module.
$ go get go

# Upgrade the suggested Go toolchain, leaving the minimum Go version alone.
$ go get toolchain

# Upgrade to the latest patch release of the suggested Go toolchain.
$ go get toolchain@patch

go install

https://go.dev/ref/mod#go-install

格式:go install [build flags] [packages]

# Install the latest version of a program,
# ignoring go.mod in the current directory (if any).
$ go install golang.org/x/tools/gopls@latest

# Install a specific version of a program.
$ go install golang.org/x/tools/gopls@v0.6.4

# Install a program at the version selected by the module in the current directory.
$ go install golang.org/x/tools/gopls

# Install all programs in a directory.
$ go install ./cmd/...

go install 命令会构建并安装由命令行上指定路径的包。可执行文件(主包)会被安装到由 GOBIN 环境变量指定的目录中,如果 GOPATH 环境变量未设置,则默认为 $GOPATH/bin 或 $HOME/go/bin。

而对于 $GOROOT 中的可执行文件,其会被安装在 $GOROOT/bin 或 $GOTOOLDIR 中,而不是 $GOBIN 中。

非可执行包会被构建并缓存,但不会被安装。 比如执行:

 go install fyne.io/fyne/v2@latest

会得到下面的输出:

go: downloading fyne.io/fyne/v2 v2.4.0
package fyne.io/fyne/v2 is not a main package

go get 不同,go install 命令可以在不存在 go.mod 文件的目录下运行