I have seen possible duplicate questions but they seem to suggest use of go modules. But I was wondering why the well documented functionality of GOPATH doesn't work out of the box:-
the import path P denotes the package found in the directory DIR/src/P for some DIR listed in the GOPATH environment variable (For more details see: 'go help gopath').
I am trying to use root.go from the file main.go
~/src/github.com/himanshugarg/sicp/root$ ls
main.go root.go test.go
The file root.go has the package declaration:-
~/src/github.com/himanshugarg/sicp/root$ head root.go
// Find square root using Newton's method
// Based on SICP's on page 30
package root
import (
"math"
);
func Sqrt(x float64) float64{
goodEnough := func (guess float64) bool {
And the file main.go imports root:-
~/src/github.com/himanshugarg/sicp/root$ head main.go
package main
import (
"fmt"
"os"
"strconv"
"github.com/himanshugarg/sicp/root"
);
func main() {
GOPATH is set correctly:-
~/src/github.com/himanshugarg/sicp/root$ echo $GOPATH
/home/hgarg
But the build fails:-
~/src/github.com/himanshugarg/sicp/root$ go build main.go
main.go:7:3: no required module provides package github.com/himanshugarg/sicp/root: go.mod file not found in current directory or any parent directory; see 'go help modules'
Surely I can use go modules but I just want to be sure that GOPATH no longer works or that I am not missing something.
CodePudding user response:
This link posted in a now deleted comment - https://go.dev/ref/mod#mod-commands - provides an explanation for this seemingly (GO)PATH breaking change:-
Most go commands may run in Module-aware mode or GOPATH mode. In module-aware mode, the go command uses go.mod files to find versioned dependencies, and it typically loads packages out of the module cache, downloading modules if they are missing. In GOPATH mode, the go command ignores modules; it looks in vendor directories and in GOPATH to find dependencies.
As of Go 1.16, module-aware mode is enabled by default, regardless of whether a go.mod file is present. In lower versions, module-aware mode was enabled when a go.mod file was present in the current directory or any parent directory.
Further:-
Module-aware mode may be controlled with the GO111MODULE environment variable, which can be set to on, off, or auto.
If GO111MODULE=off, the go command ignores go.mod files and runs in GOPATH mode.
By turning GO111MODULE off I am able to use GOPATH as documented.