首页

/

归档

/

友链

/

Github

/

模拟面试

/

独立黑客

/

资料

/

订阅

/

RSS

/

关于我


Go Module 简明教程

用惯了dep,突然换到 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.

翻译一下:

注意有几个坑的地方:

$ cat main.go
package main

func main() {
    println("Hello world")
}
$ go mod init
go: cannot determine module path for source directory /Users/jiajun/hello (outside GOPATH, no import comments)
$ vim go.mod
$ cat go.mod
module github.com/jiajunhuang/hello
$ go mod init
go mod init: go.mod already exists
$ rm go.mod
$ vim main.go
$ cat main.go
package main // import "github.com/jiajunhuang/hello"

func main() {
    println("Hello world")
}
$ go mod init
go: creating new go.mod: module github.com/jiajunhuang/hello
$ ls
go.mod  main.go
$ cat go.mod
module github.com/jiajunhuang/hello

当然,如果在已有代码的仓库里执行是不存在这个问题的。

go moddep 比较

一个生成的 go.mod 的示例

module github.com/my/module/v3  // 这是你的包的声明

// require 里是依赖需要带上路径和版本require (
    github.com/some/dependency v1.2.3
    github.com/another/dependency v0.1.0
    github.com/additional/dependency/v4 v4.0.0
)