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

 

posted @   夏秋初  阅读(2486)  评论(4编辑  收藏  举报
编辑推荐:
· .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 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示