go如何通过module新建公共包,并导入使用

一、创建一个 Go Modules 项目

1、创建文件夹

mkdir tool && cd tool

2、初始化包 go mod init github.com/hisheng/tool

➜  go mod init github.com/hisheng/tool
go: creating new go.mod: module github.com/hisheng/tool

说明:我们把代码包发到 github上。
go如何通过module新建公共包,并导入使用_第1张图片

3、添加业务代码

新建tool.go文件

➜ touch tool.go    

写入代码

package tool

func Hello() string {
    return "hello from tool project"
}

二、发布到github远程代码仓库

git init
git add .
git commit -m "init"
git remote add origin https://github.com/hisheng/tool.git
git push -u origin master

三、如何拉取导入公共包

1、拉取包到本地

➜ go get github.com/hisheng/tool

2、在代码里导入

import (
    "github.com/hisheng/tool"
    "testing"
)

func TestName(t *testing.T) {
    t.Log(tool.Hello())
}

输出:

hello from tool project

谢谢您的观看,欢迎关注我的公众号。

go如何通过module新建公共包,并导入使用_第2张图片

你可能感兴趣的:(go)