官方教程地址:https://golang.google.cn/doc/tutorial/call-module-code
1.在代码目录创建一个目录greetings用来存放greetings模块
2.生成go.mod文件
//官方文档写的是example.com/greetings,我这边按照文件夹名字设置的greetings //下面只运行一个 //官方 gomodinitexample.com/greetings //本文章 gomodinitgreetings3.创建greetings.go文件,并写入
packagegreetings import"fmt" //Helloreturnsagreetingforthenamedperson. funcHello(namestring)string{ //Returnagreetingthatembedsthenameinamessage. message:=fmt.Sprintf("Hi,%v.Welcome!",name) returnmessage }4.当前目录在greetings,返回上一级并创建一个文件夹hello。
进入hello文件夹,创建hello.go并写入
packagemain
import( "fmt" //此处导入的名字和生成go.mod的命名相同,官网是"example.com/greetings",本文章改成了“greetings” //官网引入 //"example.com/greetings" //本文章引入 "greetings" )
funcmain(){ //Getagreetingmessageandprintit. message:=greetings.Hello("Gladys") fmt.Println(message) }
6.生成hello的go.mod
gomodinithello7.设置引入模块路径,编辑hello/go.mod
//源文件应该是这样 modulehello //go的版本和你安装使用的版本相同 go1.14修改为
modulehello go1.14 //官方文档 //replaceexample.com/greetings=>../greetings //本文章 replacegreetings=>../greetings8.编译
gobuild9.查看hello/go.mod应该会变成
modulehello go1.14 replaceexample.com/greetings=>../greetings requireexample.com/greetingsv0.0.0-00010101000000-000000000000LinuxorMac执行
./hello
Windows执行
hello.exe本文内容总结:
原文链接:https://www.cnblogs.com/xiaqiuchu/p/14196882.html