文件结构如下:
第一种:使用package方式。(此方法比较推荐)
hello中.go文件的package为hello,重点:hello中不能有go.mod文件,也就是不能使用go mod init。
module目录下的go.mod中定义模块的名字为module_test。
module目录下的main.go中调用package中的函数时, 使用import "module_test/hello"
第二种方法:
(1)使用module模式。
要在hello目录下go mod init hello_test,定义hello_test模块。
go.mod定义如下:
要点:./hello的意思是在go.mod所在目录下的hello文件夹中寻找hello_test模块。
包含本地hello_test模块时,也可以只写 replace hello_test => ./hello,然后当我们调用go mod tidy时,会自动require需要的模块,如下:
main.go调用hello文件夹下函数,import如下:
注意第二处的红色方框,依然使用package(hello)进行调用。
将module当作一个单独的库使用即可。
(2)两个模块在不同文件夹下。
module_repo和modue(上方module文件夹)同一级。
module_repo文件夹下,有hello(package)目录,hello目录下是没有go.mod文件的,也就是hello目录不做为module使用。
go.mod中定义模块为module_ex。如下:
此时,我们想让模块module中的main函数调用module_ex的hello(package)中的函数。
文件夹module中go.mod。如下:
文件夹module中main.go。如下: