go module使用

Go code is grouped into packages, and packages are grouped into modules.

go的代码组成了package包,而package包组成了modules.

也就是包是独立的,modules包含了许多包。

一、创建module

1.1创建greetings目录

cd

mdkir greetings

cd greetings

使用go mod init命令创建一个go.mod文件

go mod init example.com/greetings

greeting.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
}

创建和greetings目录同级的hello目录

cd ..
mkdir hello
cd hello

hello.go代码

package main

import (
    "fmt"

    "example.com/greetings"
)

func main() {
    // Get a greeting message and print it.
    message := greetings.Hello("Gladys")
    fmt.Println(message)
}

Create a new module for this hello package

在hello文件夹给hello包创建一个新的module

go mod init hello  (hello包)

$ go mod init hello
go: creating new go.mod: module hello

Edit the hello module to use the unpublished greetings module

编辑hello module 以使用未发布的greeting module

在hello目录下将go.mod改成

module hello

go 1.14

replace example.com/greetings => ../greetings

example.com/greetings表示在import时将要使用的方式,如下:

import (
    "fmt"

    "example.com/greetings"
)

Here, the replace directive tells Go to replace the module path (the URL example.com/greetings) with a path you specify. In this case, that's a greetings directory next to the hello directory.

这个replace用法:告诉go使用你指定的一个路径去替换module路径(url 地址: example/greetings),像这个例子,那表示有一个greetings 目录与hello目录同级,如下搜索确认同级别目录。

[root@ol7-19 ~]# ls |grep -E -i -w 'hello|greetings'
greetings
hello
[root@ol7-19 ~]#

-E表示启用正则匹配,-w完全匹配单词,-i 忽略大小写

$ go build
go: found example.com/greetings in example.com/greetings v0.0.0-00010101000000-00000000000

再次查看go.mod文件,已经被go build命令改变成如下:

module hello

go 1.14

replace example.com/greetings => ../greetings

require example.com/greetings v0.0.0-00010101000000-000000000000

 go build命令编译modul时,会到../greetings目录查找本地代码,然后添加require指示命令来个指示hello package是依赖于(需要)example.com/greetings这个module,

这个依赖是在hello.go中import  了greetimgs 包的时候创建的。而replace 指示命令告诉go到哪里去找greetings这介module,因为它还没发布。

要引用一个已发布的module,go 会省略replace指令,并且会在结尾使用包含版本号的require指令:

require example.com/greetings v1.1.0

到hello目录,运行可hello可执行文件:

$ ./hello
Hi, Gladys. Welcome!

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值