Description:

In the process of learning golang, in $GOPATH/src/github.com/xxx/hello directory performs go build and go test will be submitted to the following error

go: cannot find main module; see ‘go help modules’

Solution:

Since GO111MODULE=on was set earlier, use the following command to solve the problem

$ go mod init hello
Copy the code

A go. Mod file is generated, and go Build succeeds

The reason:

In order to improve the download speed of dependent packages, we used GoProxy and then started it with the following command

$ go env -w GO111MODULE=on
$ go env -w GOPROXY=https://goproxy.cn,direct
Copy the code

This changes the default way go manages dependencies to go Module mode, which relies on a go.mod file that describes the packages and versions the project depends on (similar to NPM package.json, Maven’s POM.xml).

And there is no go.mod file in the directory, so go doesn’t know what the main module is, so it can’t compile

Delve into

When the go language was born, it did not provide package management tools. Instead, it used go Get to download dependent packages and put them in $GOPATH/SRC. It did not use version control, because it would pull the code from the master branch every time. The code for the package is placed under SRC /github.com/xx/xx

Versions after Go 1.11 introduced the Go Modules, which use versions of packages marked in go.mod, the code for which is placed under PKG /mod

Use Go Modules or GOPATH

Go uses an environment variable, GO111MODULE, to decide whether to use Go Modules or GOPATH, which has three values and different semantics across versions

value 1.11 & 1.12 1.13
GO111MODULE = on Go.mod is mandatory both inside and outside GOPATH Go.mod is mandatory both inside and outside GOPATH
GO111MODULE = off Force Go to behave GOPATH, even outside of GOPATH Force Go to behave GOPATH, even outside of GOPATH
GO111MODULE = auto Outside GOPATH, GO111MODULE = on, inside GOPATH, GO111MODULE = off GO111MODULE = on when there is go.mod or outside of GOPATH, GO111MODULE = off when there is no go.mod file inside GOPATH