> 文档中心 > go mod 简介及使用

go mod 简介及使用


目的

记述 go mod 使用

介绍

Go mod 是 Go 1.11 提出的开发包管理工具,在此之前go发布过许多包管理方案,但都强依赖于环境变量GOPATH,存在诸多缺点,不易于项目管理。

Go 之于 mod ,好比 Java 之于 maven 、 Js 之于 npm 。

它的出现使得Go语言项目脱离了对GOPATH的强依赖,为Go语言后期快速成长提供了强有力的保障。

可以使用 go help mod 查看 go mod 的使用文档

Go mod provides access to operations on modules.Note that support for modules is built into all the go commands,not just 'go mod'. For example, day-to-day adding, removing, upgrading,and downgrading of dependencies should be done using 'go get'.See 'go help modules' for an overview of module functionality.Usage: go mod  [arguments]The commands are: download    download modules to local cache edit edit go.mod from tools or scripts graphprint module requirement graph init initialize new module in current directory tidy add missing and remove unused modules vendor      make vendored copy of dependencies verify      verify dependencies have expected content why  explain why packages or modules are neededUse "go help mod " for more information about a command.

实战

一、开启 GO111MODULE

GO111MODULE 是 go 开启 mod 包管理工具的一个环境配置,共有三个配置项,分别是 off 、on 、auto 。开启mod包管理模式,可以使用选项 on 或 auto。

go env -w  GO111MODULE=auto

二、新建项目

找一个合适的地方,新建项目 go01

mkdir go01

三、初始化

进入项目目录,使用 init 初始化 go01 项目

# 进入项目目录cd go01# 初始化mod,将其mod标志设置为xzbd.com/go01go mod init xzbd.com/go01

运行后,输出

go: creating new go.mod: module xzbd.com/go01go: to add module requirements and sums: go mod tidy

四、整理项目依赖

根据建议运行推荐命令go mod tidy整理项目依赖。也可以不用运行,因为项目此时没有使用任何依赖

五、创建go01.go文件

创建 go01.go 文件,其内容如下:

package mainimport ("fmt")func main() {fmt.Println("hello go mod")}

六、运行

运行项目前可以执行go mod tidy整理项目资源,
本例中依然可以不用执行此命令,因为依赖的包fmt是go语言的标准包。

运行 go run go01.go 即可打印信息 hello go mod

总结

go mod 使用还是相对简单的,笔者在此做了简单记录

项目结构:
go mod 简介及使用

开发者涨薪指南 go mod 简介及使用 48位大咖的思考法则、工作方式、逻辑体系51声卡推荐网