go 1.16.4: go mod tidy的用途

一,查看帮助:

1,查看原始文档

liuhongdi@lhdpc:/data/go/mod3$ go help mod tidy
usage: go mod tidy [-e] [-v]

Tidy makes sure go.mod matches the source code in the module.
It adds any missing modules necessary to build the current module's
packages and dependencies, and it removes unused modules that
don't provide any relevant packages. It also adds any missing entries
to go.sum and removes any unnecessary ones.

The -v flag causes tidy to print information about removed modules
to standard error.

The -e flag causes tidy to attempt to proceed despite errors
encountered while loading packages.

See https://golang.org/ref/mod#go-mod-tidy for more about 'go mod tidy'.

2,说明:可以看到go mod tidy命令的作用:

添加需要用到但go.mod中查不到的模块,

删除未使用的模块

说明:刘宏缔的go森林是一个专注golang的博客,
          地址:https://blog.csdn.net/weixin_43881017

说明:作者:刘宏缔 邮箱: [email protected]

二,演示:删除未使用的模块

1,查看go.mod的内容:

liuhongdi@lhdpc:/data/go/mod3$ more go.mod 
module mod3

go 1.16

require github.com/gin-gonic/gin v1.7.2 // indirect

2,安装gorm2

liuhongdi@lhdpc:/data/go/mod3$ go get -u gorm.io/gorm
go: downloading gorm.io/gorm v1.21.10
go: downloading github.com/jinzhu/inflection v1.0.0
go: downloading github.com/jinzhu/now v1.1.2
go get: added gorm.io/gorm v1.21.10

再度查看go.mod

liuhongdi@lhdpc:/data/go/mod3$ more go.mod 
module mod3

go 1.16

require (
        github.com/gin-gonic/gin v1.7.2 // indirect
        gorm.io/gorm v1.21.10 // indirect
)

可以看到gorm已添加到go.mod

3,执行tidy命令后再查看效果

liuhongdi@lhdpc:/data/go/mod3$ go mod tidy
go: downloading github.com/go-playground/assert/v2 v2.0.1
go: downloading gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405

再度查看go.mod

liuhongdi@lhdpc:/data/go/mod3$ more go.mod 
module mod3

go 1.16

require github.com/gin-gonic/gin v1.7.2

可以看到因为我们还未在代码中使用新添加的gorm2,

所以gorm2模块被go mod tidy命令移除了

三,演示:添加已使用但go.mod中不存在的模块:

1,手动从go.mod中删除gin模块的引用

liuhongdi@lhdpc:/data/go/mod3$ vi go.mod

完成后查看go.mod

liuhongdi@lhdpc:/data/go/mod3$ more go.mod
module mod3

go 1.16

2,执行tidy

liuhongdi@lhdpc:/data/go/mod3$ go mod tidy
go: finding module for package github.com/gin-gonic/gin
go: found github.com/gin-gonic/gin in github.com/gin-gonic/gin v1.7.2

再度查看go.mod

liuhongdi@lhdpc:/data/go/mod3$ more go.mod
module mod3

go 1.16

require github.com/gin-gonic/gin v1.7.2

因为我们在代码中使用了gin模块,
所以go mod tidy 自动为我们在go.mod添加上了刚才已被添加的gin模块

四,查看go的版本:

liuhongdi@lhdpc:/data/go/mod3$ go version
go version go1.16.4 linux/amd64

 

你可能感兴趣的:(go安装配置,go,子模块,linux,go包管理,go语言)