go mod 使用

renevy · · 777 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

go mod 简介

Go.mod是Golang1.11版本新引入的官方包管理工具用于解决之前没有地方记录依赖包具体版本的问题,方便依赖包的管理。
Go.mod其实就是一个Modules,关于Modules的官方定义为:
Modules是相关Go包的集合,是源代码交换和版本控制的单元。go命令直接支持使用Modules,包括记录和解析对其他模块的依赖性。Modules替换旧的基于GOPATH的方法,来指定使用哪些源文件。
Modules和传统的GOPATH不同,不需要包含例如src,bin这样的子目录,一个源代码目录甚至是空目录都可以作为Modules,只要其中包含有go.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 <command> [arguments]

The commands are:

download    download modules to local cache
edit        edit go.mod from tools or scripts
graph       print 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 needed

Use "go help mod <command>" for more information about a command.

go mod 构建新项目

  1. 任意目录创建新建项目hello
├── hello.go
└── tests
    └── test.go

hello.go

package main

import (
    "fmt"
    test "test/tests"
    _ "github.com/gohouse/gorose"
)

var tes = "local test."

func init() {
    fmt.Println(tes)
}

func main() {
    fmt.Println("Hello world!")
    test.Say()

}

test.go

package test

import "fmt"

// 初始化函数  引入包的时候要先执行 可以重复定义多个 同一个go文件从上到下  多个文件 是按照字符串进行排序 从小到大 执行 a>b>c
// 不同包 引入包的顺序执行

func init() {
    fmt.Println(" 我是初始化函数 2")
}

func init() {
    fmt.Println(" 我是初始化函数 1")
}

func Say() {
    fmt.Println("i am test")
}
  1. go mod init test 初始化module
ls
go.mod  hello.go  tests

cat go.mod 
module hello

go 1.14
go run hello.go 
 我是初始化函数 2
 我是初始化函数 1
local test.
Hello world!
i am test

go mod文件中的依赖的第三方包会下载到 $GOPATH/pkg/mod路径下.

在旧项目项目中使用 go mod

  1. cd 进入目录,运行 go mod init + module name
  2. go build 或者 go run 一次

有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:renevy

查看原文:go mod 使用

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

777 次点击  
加入收藏 微博
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传