似乎自 1.11 以来模块的使用方式发生了变化,我试图了解如何从另一个目录引用模块/包。
假设我有一个文件夹结构 \root\module1 \root\module2
我在每个目录中有一个 go.mod,我可以从 \root 目录访问/使用这些模块
如何从模块 1 访问模块 2。这些模块未在任何地方发布(我也不希望它们发布)-我只想访问它们。模块 2 包含我需要在 mondule1 中使用的类型/结构
亲切的问候马丁
Go 模块必须放在 GOPATH 中才能使用。
当我开始一个新的 go 项目时,我通常会在 gopath 中创建一个文件夹
cd $GOPATH
ls
Run Code Online (Sandbox Code Playgroud)
在这里你可以找到 3 个文件夹
bin pkg src
ls src
>code.cloudfoundry.org github.com github.ibm.com golang.org gopkg.in go.uber.org honnef.co winterdrache.de
Run Code Online (Sandbox Code Playgroud)
在 src 中,有您使用“go get”命令检索的代码。
此处的所有内容都可以导入(/导出)到您的软件中。
假设这个测试项目:
github.ibm.com/
??? Alessio-Savi
??? GoLog-Viewer
??? conf
? ??? dev.json
? ??? test.json
??? database
? ??? cloudant
? ? ??? cloudant.go
? ??? db2
? ??? db2.go
??? datastructure
? ??? datastructures.go
??? GinProva.go
??? README.md
??? request
? ??? request.go
??? resources
??? template01.html
Run Code Online (Sandbox Code Playgroud)
注意:数据结构保存在正确目录中的 go 文件中,以避免循环导入
您可以使用以下导入语句导入 datastructure.go(或您需要的其他文件)
bin pkg src
ls src
>code.cloudfoundry.org github.com github.ibm.com golang.org gopkg.in go.uber.org honnef.co winterdrache.de
Run Code Online (Sandbox Code Playgroud)
在其他文件中(与其他文件在同一个项目中),您可以简单地使用该包并让 IDE 帮助您(因为模块/项目在 GOPATH 中)
为了创建一个新模块,您可以使用新的go module init
gotool 命令。
在公共源代码的情况下,创建新模块的常用方法如下:
github.ibm.com/
??? Alessio-Savi
??? GoLog-Viewer
??? conf
? ??? dev.json
? ??? test.json
??? database
? ??? cloudant
? ? ??? cloudant.go
? ??? db2
? ??? db2.go
??? datastructure
? ??? datastructures.go
??? GinProva.go
??? README.md
??? request
? ??? request.go
??? resources
??? template01.html
Run Code Online (Sandbox Code Playgroud)
这将生成两个文件:
该go.mod
文件将包含运行模块所需的每个库/外部 golang 代码。该go.sum
文件将包含库的哈希值。
例如,我将使用我的小型通用库,名为GoGPUtils
.
package mypackage
import(
"github.ibm.com/Alessio-Savi/GoLog-Viewer/datastructure"
)
Run Code Online (Sandbox Code Playgroud)
现在,您可以在库中的代码中插入您需要的go.mod
库。假设您需要ahocorasick
使用字符串搜索的实现,该go.mod
文件将包含以下内容:
module github.com/alessiosavi/GoGPUtils
go 1.13
require (
github.com/alessiosavi/ahocorasick v0.0.3
golang.org/x/tools v0.0.0-20191031220737-6d8f1af9ccc0 // indirect
)
Run Code Online (Sandbox Code Playgroud)
在该require
部分中,有所需的包列表。现在您可以ahocorasick
在代码中导入库,如下所示:
go mod init github.com/username/modulename
Run Code Online (Sandbox Code Playgroud)