likes
comments
collection
share

Golang里面go.mod文件内容版本号简单用法

作者站长头像
站长
· 阅读数 16

本文go版本是1.14,开启GO111MODULE="on"

经常在go.mod里面看到引入第三方库的版本号:

module test

go 1.14

require github.com/jinzhu/copier v0.3.5 // indirect

可以看到copier版本使用的是v0.3.5的版本。

现在做个实验,在go.mod里面写上上面的代码【是手动写入,没有下载】

我们假定main.go内容如下:

package main

import "fmt"

func main() {
	fmt.Println("test")
} 

里面没有使用到copier的库,我们先run一下

Golang里面go.mod文件内容版本号简单用法

可以看到代码正常运行,但是它并没有下载这个依赖包。

现在改一下main.go的代码,如下:

package main

import (
	"fmt"
	"github.com/jinzhu/copier"
)

type User struct {
	Name string
	Age  int
	QQ   string
}

type Employee struct {
	Name string
	Age  int
	Role string
}

func main() {
	user := User{Name: "dj999", Age: 18, QQ: "8888"}
	employee := Employee{Role: "xxx"}

	copier.Copy(&employee, &user)
	fmt.Printf("%#v\n", employee)
} 

直接运行go run main.go

Golang里面go.mod文件内容版本号简单用法

可以看到它自动下载这个库的指定版本了(go: downloading github.com/jinzhu/copier v0.3.5),并且代码运行成功。

这个时候在pkg\mod\github.com\jinzhu下也有这个扩展库的文件夹了

Golang里面go.mod文件内容版本号简单用法

我们换一个场景:把go.mod内容改一下:

module yif

go 1.14

require github.com/jinzhu/copier v0.3.4 // indirect 

就是把版本号改为v0.3.4,其他不变,run一下

Golang里面go.mod文件内容版本号简单用法

发现它下载了v0.3.4的版本了,再来看看pkg\mod\github.com\jinzhu目录:

Golang里面go.mod文件内容版本号简单用法

发现两个都存在了。

所以go.mod的一个功能就是指定特定版本,让项目组每个开发者使用同一个版本号进行开发