Go Cli工具详解(get,install,clean等)

最后编辑于 2021-03-19

本文总结了 Go 1.16 后 Go 命令行工具使用需要注意的地方

文章一开头需要明确一下module的定义,一个module就是很多package的集合,一个包含 go.mod 的文件夹就是一个module,其包含了该文件夹下面的所有 package,当然还存在 module 嵌套的情况,比较少见不作讨论。

get

使用示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
# Upgrade a specific module.
$ go get -d golang.org/x/net

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

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

# Update to the commit on the module's master branch.
$ go get -d 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 -d golang.org/x/text@none

官方文档给 get 的定义是:

The go get command updates module dependencies in the go.mod file for the main module, then builds and installs packages listed on the command line. Go 命令更新 main module 在 go.mod 文件中的依赖项,然后编译安装二进制

可以看到,go 1.16 中 get 还是有安装二进制的功能的,但是官方更推荐 install 来安装二进制,之后版本 get 安装二进制的功能会被去掉,所以给项目添加依赖只需要用go get -d <module-path>,这里的 d 告诉 get 下载完源码后停止:

The -d flag instructs get not to build or install packages. get will only update go.mod and download source code needed to build packages.

Install

Go 1.16 的更新日志中提到:

go install, with or without a version suffix (as described above), is now the recommended way to build and install packages in module mode. go get should be used with the -d flag to adjust the current module’s dependencies without building packages, and use of go get to build and install packages is deprecated. In a future release, the -d flag will always be enabled.

推荐go install用于构建及安装 packages,go get 应该搭配-d一起使用,不推荐使用go get来构建安装 packages。

The go install command builds and installs the packages named by the paths on the command line. Executables (main packages) are installed to the directory named by the GOBIN environment variable

go install将 packages 构建并安装到$GOBIN里。

使用示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# 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/...

参考资料: