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 download$GOPATH/pkg/mod/cachego mod editgo.modgo mod edit -fmt go.modgo.modgo mod graphgo mod initgo mod tidygo mod vendorvendor/go mod verifygo mod why

注意有几个坑的地方:

go mod$GOPATHGO111MODULEauto$GOPATHongo mod initmain.go
$ 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 modGOPROXYgo moddepgo.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
)