1如何管理依赖
-
以模块为单位管理依赖
Go code is grouped into packages, and packages are grouped into modules.
Go源代码=>Go 包(Package)=>Go 模块(Module)
在Go中,你可以以模块为单位管理你需要import的依赖。

3. 定位和导入有用的包

其中rsc.io/quote是module path
-
在你的代码中启动依赖追踪
为了追踪和管理你代码中要添加的依赖,你要把自己的代码放入到自己定义的模块中=>创建go.mod文件
go mod init <module-path> //If possible, the module path should be the repository location of your source code-
命名模块module path:首先确保的module path与其他模块没有冲突
格式:/

-
-
同步你的代码的依赖关系
go mod tidy -v //-v是打印被删除的模块目的:保持你的代码依赖的完整性和整洁性,go mod tidy会自动修改go.mod文件添加并下载你需要的依赖但是还没下载到本地的,删除你不需要的依赖
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JOz2MRC2-1654824102111)(Managing dependencies.assets/image-20220607112147986-16545721092613.png)]](https://i-blog.csdnimg.cn/blog_migrate/f2841be3a5fce225ed5b0df7086c18a2.png)
6. 开发和测试未发布的模块代码
场景:[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-eO3p5PUL-1654824102112)(Managing dependencies.assets/image-20220607112454034-16545722950134.png)]
go mod edit -replace=example.com/theirmodule@v0.0.0-unpublished=../theirmodule
//把example.com/theirmodule@v0.0.0-unpublished重定向至../theirmodule模块
//或者你可以把example.com/theirmodule@v0.0.0-unpublished重定向至已经发布的模块
//但是重定向至已发布的模块必须要指明指向哪个版本即@版本号
-
把下载的依赖包放到项目內部,而不是放在$GOPATH/pkg/mod的module-cache中
The
go mod vendorcommand constructs a directory namedvendorin the main module’s root directory containing copies of all packages needed to build and test packages in the main module.go mod vendor//在module-path的根目录下创建一个vendor文件夹,并且依赖包下载至vendor下go mod vendor作用:
- 创建名为vendor的文件夹
- 将该module的所有依赖包都放置在该vendor文件夹中
- 在该vendor文件夹中创建modules.txt文件,表明vendor文件夹中包名+版本号
2go.mod文件参考
- go.mod文件的组成:
![[外链图片转存失败,源站可能有防盗链机
制,建议将图片保存下来失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UUGfLsPQ-1654824102116)(Managing dependencies.assets/image-20220607113856469-16545731372995.png)(Managing dependencies.assets/image-20220607113856469-16545731372995.png)]](https://i-blog.csdnimg.cn/blog_migrate/3092180d84a4dd0f1c07da8c7c37c778.png)
- module path:Go tools可以下载该module的路径(如果该模块还没发布必须要用go mod edit -replace将模块路径重定向至本地的模块路径使得可以使用该模块)
- go:该模块使用的最低版本的Go
- module requires:该模块使用其他最低版本的模块列表
对于Module部分:
- 语法:module

- 例子:


本文介绍了在Go中如何以模块为单位管理依赖,包括创建go.mod文件、使用`go mod tidy`同步依赖、利用`go mod vendor`管理本地依赖以及`go mod edit -replace`用于开发未发布的模块。此外,还提到了go.mod文件的结构,如module path、Go版本和依赖列表。
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AM38AI80-1654824102117)(Managing dependencies.assets/image-20220607114827997.png)]](https://i-blog.csdnimg.cn/blog_migrate/4844690902257d4025f8e5fc9ff5c19c.png)
2806

被折叠的 条评论
为什么被折叠?



