golang实现自己的模块并调用
官方教程地址:https://golang.google.cn/doc/tutorial/call-module-code
1.在代码目录创建一个目录greetings 用来存放 greetings 模块
2.生成go.mod文件
// 官方文档写的是example.com/greetings,我这边按照文件夹名字设置的 greetings // 下面只运行一个 // 官方 go mod init example.com/greetings // 本文章 go mod init greetings
3.创建greetings.go文件,并写入
package greetings import "fmt" // Hello returns a greeting for the named person. func Hello(name string) string { // Return a greeting that embeds the name in a message. message := fmt.Sprintf("Hi, %v. Welcome!", name) return message }
4.当前目录在 greetings ,返回上一级并创建一个文件夹 hello。
5. 进入hello文件夹,创建 hello.go 并写入
package main import ( "fmt" // 此处导入的名字和生成go.mod的命名相同,官网是"example.com/greetings",本文章改成了 “greetings” // 官网引入 // "example.com/greetings" // 本文章引入 "greetings" ) func main() { // Get a greeting message and print it. message := greetings.Hello("Gladys") fmt.Println(message) }
6.生成hello的go.mod
go mod init hello
7.设置引入模块路径,编辑 hello/go.mod
// 源文件应该是这样 module hello // go的版本和你安装使用的版本相同 go 1.14
修改为
module hello go 1.14 // 官方文档 // replace example.com/greetings => ../greetings // 本文章 replace greetings => ../greetings
8.编译
go build
9.查看 hello/go.mod 应该会变成
module hello go 1.14 replace example.com/greetings => ../greetings require example.com/greetings v0.0.0-00010101000000-000000000000
10. Linux or Mac 执行
./hello
Windows 执行
hello.exe
博 主 :夏秋初
地 址 :https://www.cnblogs.com/xiaqiuchu/p/14196882.html
如果对你有帮助,可以点一下 推荐 或者 关注 吗?会让我的分享变得更有动力~
转载时请带上原文链接,谢谢。
地 址 :https://www.cnblogs.com/xiaqiuchu/p/14196882.html
如果对你有帮助,可以点一下 推荐 或者 关注 吗?会让我的分享变得更有动力~
转载时请带上原文链接,谢谢。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义