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 @ 2020-12-27 12:29  夏秋初  阅读(2371)  评论(4编辑  收藏  举报