go install和go get的区别实例详解

go get 和 go install 的区别

先看结论:

  • go get: 对 go mod 项目,添加,更新,删除 go.mod 文件的依赖项(仅源码)。不执行编译。侧重应用依赖项管理。
  • go install: 在操作系统中安装 Go 生态的第三方命令行应用。不更改项目 go.mod 文件。侧重可执行文件的编译和安装。

之前网上乱传的 go get 命令要被弃用是错的。正确说法是,go 1.17后,go get 命令的使用方式发生了改变.

具体什么改变呢?请看官方说明:

Starting in Go 1.17, installing executables with go get is deprecated. go install may be used instead.

In Go 1.18, go get will no longer build packages; it will only be used to add, update, or remove dependencies in go.mod.

Specifically, go get will always act as if the -d flag were enabled.

大概表达3个意思:

  • Go 1.17 起, 弃用 go get 命令安装可执行文件,使用 go install 命令替代.
  • Go 1.18起,go get 命令不再有编译包的功能。将只有添加,更新,移除 go.mod 文件中的依赖项的功能。
  • go get 命令将默认启用 -d 选项。

go get命变更

  • Go 1.17 之前:go get 通过远程拉取或更新代码包及其依赖包,并自动完成编译和安装。实际分成两步操作:1. 下载源码包,2. 执行 go install。
  • Go 1.17 之后: 弃用go get命令的编译和安装功能

go get命令变更的原因

由于 go 1.11 之后 go mod modules特性的引入,使得go get 命令,既可以安装第三方命令,又可以从 go.mod 文件自动更新项目依赖。但多数情况下,开发者只想做二者之一。

go 1.16 起,go install 命令,可以忽略当前目录的 go.mod文件(如果存在),直接安装指定版本的命令行应用。

go get 命令的编译和安装功能,因为和 go install 命令的功能重复,故被弃用。由于弃用了编译和安装功能,go get 命令将获得更高的执行效率, 也不会在更新包的时候,再出现编译失败的报错。

Since modules were introduced, the go get command has been used both to update dependencies in go.mod and to install commands.

This combination is frequently confusing and inconvenient: in most cases, developers want to update a dependency or install a command but not both at the same time.

Since Go 1.16, go install can install a command at a version specified on the command line while ignoring the go.mod file in the current directory (if one exists).

go install should now be used to install commands in most cases.

go get’s ability to build and install commands is now deprecated, since that functionality is redundant with go install.

Removing this functionality will make go get faster, since it won’t compile or link packages by default.

go get also won’t report an error when updating a package that can’t be built for the current platform.

go get 由于具备更改 go.mod 文件的能力,因此我们 必须要避免执行 go get 命令时,让它接触到我们的 go.mod 文件 ,否则它会将我们安装的工具作为一个依赖。

所以,如果不是为了更新项目依赖,而是安装可执行命令,请使用 go install

GOMODULE常用命令

go mod init  # 初始化go.mod
go mod tidy  # 直接从源代码中获取依赖关系,更新依赖文件。可删掉go.mod中无用的依赖。
go mod download  # 下载依赖文件
go mod vendor  # 将依赖转移至本地的vendor文件
go mod edit  # 手动修改依赖文件
go mod graph  # 打印依赖图
go mod verify  # 校验依赖

在项目源码中使用 import 语句,导入新的依赖模块前,可用 go get 命令,先下载新模块。

go instsll 应该在module外部使用 https://github.com/golang/go/issues/40276

弃用go get命令安装可执行文件 https://go.dev/doc/go-get-install-deprecation

Go 1.16 中关于 go get 和 go install https://cloud.tencent.com/developer/article/1766820

总结

原文地址:https://blog.csdn.net/WHQ78164/article/details/128081577