Go Module简介 | 青训营笔记

104 阅读1分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 5 天

有些地方感觉英文写的很好,或者说中文我不知道该怎么翻译,就直接用的英文 🤣

Go Module介绍

看英文介绍比较清楚

A module is a collection of Go packages stored in a file tree with a go.mod file at its root. The go.mod file defines the module’s module path, which is also the import path used for the root directory, and its dependency requirements, which are the other modules needed for a successful build.

Each dependency requirement is written as a module path and a specific semantic version.

  1. module由一系列包组成,每个包都是一系列同目录下、将被编译到一起的文件集合
  2. module根目录是指包含go.mod文件的目录
  3. module path 描述模块做什么以及在哪里找到它,被go.mod文件中的module指令声明

依赖管理

创建新的module

go mod init会在工作目录创建一个go.mod文件,可以使用cat go.mod命令查看go.mod文件的内容

$ go mod init 工作目录的相对路径

go.mod文件只在module的根目录存在。子目录中自动被识别成同一个module,同时import path就是根目录+子目录路径。因此没必要在子目录执行go mod init命令


添加依赖

go命令会导入在go.mod文件中列出来的特定版本的依赖。若import的package没有在go.mod中显示,那么go命令会自动把它的最新版本添加到go.mod文件。例如

package hello

import "rsc.io/quote"

func Hello() string {
    return quote.Hello()
}

执行go test会发现程序自动导入依赖的过程。当我们再执行cat go.mod命令时,会发现依赖已经被导入了

module example.com/hello

go 1.12

require rsc.io/quote v1.5.2

此时若再次执行go test不会出现之前的过程,因为此时的go.mod文件已经是最新的了。


升级依赖(minor version)

经常可以见到版本号形如v0.1.2,那么这三个数字分别是什么意思呢?
—— 这里0 是 major version,1 是 minor version,2 是 patch version

这一节主要介绍minor version的升级 直接执行

$ go get 依赖名称
$ go test

即可

若出现错误,则可以先用go list -m -versions 依赖名称查看可用的版本,然后用go get 依赖名称@v1.3.1来指定特定版本的依赖


Adding a dependency on a new major version

直接在代码中使用import特定major version的依赖,然后go test

但是要注意,major version不同的话,module path也不同。modula path以major version的版本号结尾,比如v1和v2就不同

一个程序可以使用多个major version不同的依赖,但是不能使用多个只是minor version 不同的依赖

The go command allows a build to include at most one version of any particular module path, meaning at most one of each major version: one rsc.io/quote, one rsc.io/quote/v2, one rsc.io/quote/v3, and so on.

This gives module authors a clear rule about possible duplication of a single module path: it is impossible for a program to build with both rsc.io/quote v1.5.2 and rsc.io/quote v1.6.0.


Upgrading a dependency to a new major version

major version改变时,要注意一些API的调用是否改变,若API在新版本中不存在,则会报错


移除无用的依赖

使用

$ go mod tidy

总结

  • go mod init creates a new module, initializing the go.mod file that describes it.
  • go build, go test, and other package-building commands add new dependencies to go.mod as needed.
  • go list -m all prints the current module’s dependencies. go get changes the required version of a dependency (or adds a new dependency).
  • go mod tidy removes unused dependencies.

参考资料

Using Go Modules - The Go Programming Language
Go 语言进阶与依赖管理 - 掘金 (juejin.cn)
Go Modules 中文文档