我使用此命令“go mod init database”在“database”文件夹中的“GOPATH”之外创建了一个库作为个人使用的模块,我不知道:
OS: Windows 7 ,Go: v1.11
最简单且开箱即用的解决方案是将您的 database 软件包/模块放入VCS(例如github.com),因此其他软件包(在其他模块中)可以通过导入它来简单地引用它:
database
import "github.com/someone/database"
如果你这样做,你甚至不必手动操作 go.mod 文件,go工具将会处理所有内容:它将自动识别并解决此依赖关系,下载并安装所需的包,并且还将更新 go.mod 自动 .
go.mod
如果你只是尝试或者你还没有决定使用什么,那么你仍然可以做到这一点 . 怎么详细的官方Go Wiki: Can I work entirely outside of VCS on my local filesystem?
因此,您在 GOPATH 之外创建了一个 database 文件夹,并在其中创建了一个模块 . 你创建了另一个模块,我们称之为 main ,你想使用这个 database 包 .
GOPATH
main
你必须做的是:
main 模块的
require ( example.com/me/database v0.0.0 )
replace
replace example.com/me/database => ../database
就这样 .
让's see a working example. Let'创建一个 pretty 模块 . 创建一个包含2个文件的 pretty 文件夹:
pretty
pretty.go:
package pretty import "fmt" func Pretty(v ...interface{}) { fmt.Println(v...) }
go.mod (可以通过运行 go mod init pretty 创建):
go mod init pretty
module pretty
现在让's create another, main module. Let'在 pretty 文件夹旁边创建一个文件夹 osinf (可能是任何内容) . 其中2个文件:
osinf
osinf.go (注意我们打算使用我们的 pretty 包/模块,我们通过 "example.com/me/pretty" 导入它):
"example.com/me/pretty"
package main import "example.com/me/pretty" func main() { pretty.Pretty("hi") pretty.Pretty([]int{1, 3, 5}) }
go.mod:
module main require example.com/me/pretty v0.0.0 replace example.com/me/pretty => ../pretty
在 osinf 文件夹中运行 go run osinf.go ,输出为:
go run osinf.go
hi [1 3 5]
1 回答
最简单且开箱即用的解决方案是将您的
database
软件包/模块放入VCS(例如github.com),因此其他软件包(在其他模块中)可以通过导入它来简单地引用它:如果你这样做,你甚至不必手动操作
go.mod
文件,go工具将会处理所有内容:它将自动识别并解决此依赖关系,下载并安装所需的包,并且还将更新go.mod
自动 .完全停留在本地磁盘上
如果你只是尝试或者你还没有决定使用什么,那么你仍然可以做到这一点 . 怎么详细的官方Go Wiki: Can I work entirely outside of VCS on my local filesystem?
因此,您在
GOPATH
之外创建了一个database
文件夹,并在其中创建了一个模块 . 你创建了另一个模块,我们称之为main
,你想使用这个database
包 .你必须做的是:
main
模块的go.mod
必须将database
包列为"requirement" . 为database
包提供临时VCS名称:replace
指令使database
包指向本地磁盘上的文件夹;你可以使用绝对和相对路径:就这样 .
工作实例
让's see a working example. Let'创建一个
pretty
模块 . 创建一个包含2个文件的pretty
文件夹:pretty.go:
go.mod (可以通过运行
go mod init pretty
创建):现在让's create another, main module. Let'在
pretty
文件夹旁边创建一个文件夹osinf
(可能是任何内容) . 其中2个文件:osinf.go (注意我们打算使用我们的
pretty
包/模块,我们通过"example.com/me/pretty"
导入它):go.mod:
就这样 .
在
osinf
文件夹中运行go run osinf.go
,输出为: