I'm new in GO and has got stuck in environment configuration for hours.
I succeeded to run some test projects, but when I tried to import my custom local packages (say xxx), the "go run" command failed, logging that:
*test/main/main.go:6:2: package test/xxx is not in GOROOT (/usr/local/go/src/test/xxx)*
It is strange that GOPATH seems to be ignored when importing local packages on my ubuntu computer.
go version is go1.16.5 linux/amd64
GOPATH is set using export GOPATH="$HOME/GoProjects"
GOROOT is set using export GOPATH="/usr/local/go"
GoMod is "on" using go env -w GO111MODULE=on
After editing project's .go files, command "go mod init" and "go mod tidy" are typed in the root folder of the project ($GOPATH/src/test), and the project file structure looks like:
/src
/.vscode
-launch.json
/gitbub.com
/test
/main
-main.go (here: import "test/xxx")
/xxx
-xxx.go (here: package xxx)
-go.mod (almost empty - line 1: module test
line 2:
line 3: go 1.16 )
What should I do to fix this problem?
First, stop worrying about GOPATH
. That is old stuff, and you don't need to do it any more. Then, make a folder somewhere test
(doesn't need to be anything to do with GOPATH
, just put in current directory, or wherever you want). Then make test/xxx
. Then make test/xxx/xxx.go
:
package xxx
const X = 1
Then make folder test/main
. Then make test/main/main.go
:
package main
import "test/xxx"
func main() {
println(xxx.X)
}
Then go back to test
, and do go mod init test
. Then go back to test/main
,
and do go build
. Done.