启动一个其他人可以使用的模块。
首先创建一个Go模块。在模块中,您为一组离散而有用的函数收集一个或多个相关包。例如,您可以创建一个带有包的模块,这些包具有进行财务分析的功能,以便编写财务应用程序的其他人可以使用您的工作。
Go代码被分组到包中,包被分组到模块中。您的模块指定了运行代码所需的依赖项,包括Go版本和它所需的其他模块集。
当您在模块中添加或改进功能时,您将发布模块的新版本。编写调用模块中函数的代码的开发人员可以导入模块的更新包,并在将其投入生产使用之前使用新版本进行测试。
前面已经做过了,建立了一个mymode目录
PS F:\learn\go-learn> cd mymode
PS F:\learn\go-learn\mymode> go mod init testpro/mymode
go: creating new go.mod: module testpro/mymode
go: to add module requirements and sums:
go mod tidy
PS F:\learn\go-learn\mymode> ls
目录: F:\learn\go-learn\mymode
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2022/12/5 18:03 31 go.mod
-a---- 2022/12/5 18:00 77 mymode.go
PS F:\learn\go-learn\mymode>cat go.mod
module testpro/mymode
go 1.19
go init命令创建一个go.mod文件调试你代码的依赖关系。目前,这个文件仅包含你模块的名字和你代码支持的go版本号,但是当您添加依赖项时,go.Mod文件将列出您的代码所依赖的版本。这样可以保持构建的可重复性,并让您直接控制使用哪个模块版本。
在文本编辑器中,创建一个文件来编写代码,并将其命名为mymode.go。
将以下代码粘贴,打开文件并保存文件。
package mymode
func MyAdd( a int, b int) int {
return a+b
}
上面代码定义了一个MyAdd函数,将两数相加再加上两数中最大的一个数,并返回结果。
package mymode声明了一个mymode包
这个文件放在mymode目录下
PS F:\learn\go-learn> mkdir test
目录: F:\learn\go-learn
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 2022/12/5 17:50 test
要为你的test代码启用依赖跟踪,运行go mod init命令,给它你的代码将在的模块的名称,使用testpro/mymode作为模块路径。
PS F:\learn\go-learn> cd test
PS F:\learn\go-learn\test> go mod init testpro/test
go: creating new go.mod: module testpro/test
go: to add module requirements and sums:
go mod tidy
PS F:\learn\go-learn\test> ls
目录: F:\learn\go-learn\test
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2022/12/5 18:02 29 go.mod
-a---- 2022/12/5 17:54 84 test.go
PS F:\learn\go-learn\test>
package main
import (
"fmt"
"testpro/mymode"
)
func main() {
result := mymode.MyAdd(10,20)
fmt.Println(result)
}
import导入了前面定义的testpro/mymode模块,然后在main函数中调用它。
result := mymode.myadd(10,20)
对于生产使用,您将从它的存储库中发布testpro/mymode模块(模块路径反映了它的发布位置),在那里Go工具可以找到它并下载它。目前,因为您还没有发布模块,所以需要调整testpro/mymode模块,以便它能够在本地文件系统上找到testpro/mymode代码
1、使用go mod edit命令编辑testpro/test模块,将go工具从模块路径(模块不在的地方)重定向到本地目录(模块在的地方)。
go mod edit -replace testpro/mymode=../mymode
该命令指定testpro/mymode应该替换为…/mymode,用于定位依赖项。运行命令后,go.mod 目录中的go.mod文件应该包含一个replace指令:
replace testpro/mymode => ../mymode
PS F:\learn\go-learn\test> go mod edit -replace testpro/mymode=../mymode
PS F:\learn\go-learn\test> cat go.mod
module testpro/test
go 1.19
replace testpro/mymode => ../mymode
PS F:\learn\go-learn\test>
2、从test目录的命令提示符中,运行go mod tidy命令来同步testpro/test模块的依赖项,添加代码需要的、但在模块中尚未跟踪的依赖项。
PS F:\learn\go-learn\test> go mod tidy
go: found testpro/mymode in testpro/mymode v0.0.0-00010101000000-000000000000
PS F:\learn\go-learn\test> cat go.mod
module testpro/test
go 1.19
replace testpro/mymode => ../mymode
require testpro/mymode v0.0.0-00010101000000-000000000000
PS F:\learn\go-learn\test>
3、在test目录中的命令提示符下,运行代码以确认其工作。
PS F:\learn\go-learn\test> go run .
30
PS F:\learn\go-learn\test>