在其他模块中调用代码
在上一节中,你创建了一个greeting 模块,在本节,你将学习如果调用模块中的hello函数.你能编写出能够执行greeting模块的应用程序.
注:本主题是"创建一个go模块的"一部分
1.新建一个名为hello的文件夹,用来存放你写的调用器.
你创建了这个目录后,当前目录下会有hello和greeting两个目录
<home>/ |-- greetings/ |-- hello/
如果你的命令提示符在greeting目录下,你可以使用如下命令:
cd ..
mkdir hello
cd hello
2.开启依赖性跟踪器,
使用 go mod init 命令就能打开依赖性跟踪器.记得,把你的模块名称传给它
比如,按照本教程的习惯,可以使用example.com/hello 作为模块路径
$ go mod init example.com/hello
go: creating new go.mod: module example.com/hello
3.在hello路径下,创建一个hello.go文件
4.编写调用hello函数的代码,然后把这个函数的返回值打印出来
把下面代码粘贴到hello.go文件中
package main import ( "fmt" "example.com/greetings" ) func main() { // Get a greeting message and print it. message := greetings.Hello("Gladys") fmt.Println(message) }
在本代码中:
- 声明了一个main包,在Go中,作为应用程序的代码段,必须含有main包
- 引入了两个包:example.com/greetings和fmt包, 这样你就能调用这些包中的函数了,引入example.com/greeting(这个包是在上节由你创建的.)以便你能够调用hello函数.仍然引入了fmt包,这里面含有文本输入和输出函数(比如把文本打印到控制台).<这个老外起的破名, 上一节有个greeting包内有hello函数,本节又创建了一个hello包,用来调用上节的hello函数. 绕弯弯的命名方式,贪吃蛇玩多了>
- 使用greeting包中的hello函数获得问候语
5.在example.com/hello模块中使用example.com/greeting模块
在生产环境下,你需要将example.com/greeting模块从代码库中发行.这样go 工具就能发现并下载它.此刻,由于你还未发布模块,你需要改变example.com/hello模块以便它在你当下系统内找到example.com/greetings模块
你可以这么做:用 go mod edit 命令改变example.com/hello模块的定位目标,以重定位到本地路径
1.在hello路径下,运行下面命令
$ go mod edit -replace example.com/greetings=../greetings
这个命令,规定了,example.com/greeting依赖路径应该被替换为../greetings. 当你运行这个命令后,go.mod文件内就应该包含了你替换的路径
module example.com/hello go 1.16 replace example.com/greetings => ../greetings
2.在hello路径,运行go mod tidy 命令来同步example.com/hello模块的依赖.
$ go mod tidy go: found example.com/greetings in example.com/greetings v0.0.0-00010101000000-000000000000
命令执行完毕后,模块的go.mod文件看起来长这样:
module example.com/hello go 1.16 replace example.com/greetings => ../greetings require example.com/greetings v0.0.0-00010101000000-000000000000
这个命令在本地greeting路径下发现了代码,然后在example.com/hello中增加一个require指令用于标识example.com/greetings是必需的.当你在hello.go引入greetings包这个依赖就会被引入.
在模块路径后的一串数字叫做伪版本号----用来代替语义版本号(模块还没有版本号)
引用一个已发行模块,go.mod文件通常会省略replace指令,并使用一个在末尾带有标记版本号的require指令。
require example.com/greetings v1.1.0
有关版本号的详细信息,请参见模块版本号。
在hello路径的命令提示符后,运行代码,看看效果:
$ go run .
Hi, Gladys. Welcome!
万岁! 你已经写了两个功能模块,接下来,你将学习到错误处理