I have the following file structure:
.
├── bin
│ └── hello
├── pkg
└── src
└── jacob.uk.com
├── greeting
│ └── greeting.go
└── helloworld.go
5 directories, 3 files
With the following GOPATH
/Users/clarkj84/Desktop/LearningGo
Upon executing /usr/local/go/bin/go install jacob.uk.com
within the src
folder, I get the error local import "./greeting" in non-local package
helloworld.go
:
package main;
import "./greeting"
func main() {
}
To import a package, we use import syntax followed by the package name. 💡 Unlike other programming languages, a package name can also be a subpath like some-dir/greet and Go will automatically resolve the path to the greet package for us as you will see in the nested package topic ahead.
Golang Import Local PackagesIn the root of your project, aka, the workspace directory, create a main.go file. In the example above, we add 3 import clauses to import all the packages in our program. Once imported, we can use the exported code in the packages.
You can't use local import when specifying a non-local package to go install
. If you want the local import to work, first change working directory to src/jacob.uk.com
then execute go install
(without specifying the package).
Of course having the helloworld.go
you provided you will get an compile error: imported and not used
. But once you use something from the imported greeting
package, it should compile.
But you shouldn't use local imports at all. Instead write:
import "jacob.uk.com/greeting"
And doing so you will be able to compile/run/install it from anywhere.
Typing go build
does not work with relative import paths; you must type go build main.go
.
go install
does not work at all with relative import paths.
It is documented at https://golang.org/cmd/go/#hdr-Relative_import_paths
See
for explanation.
You can add the local packages using replace in go 1.11<= go to your go.mod and use "replace" keyword, as below, (you do not need to create a github repo, just add the lines like this)
module github.com/yourAccount/yourModule
go 1.15
require (
github.com/cosmtrek/air v1.21.2 // indirect
github.com/creack/pty v1.1.11 // indirect
github.com/fatih/color v1.9.0 // indirect
github.com/imdario/mergo v0.3.11 // indirect
github.com/julienschmidt/httprouter v1.3.0
github.com/mattn/go-colorable v0.1.7 // indirect
github.com/pelletier/go-toml v1.8.0 // indirect
go.uber.org/zap v1.15.0
golang.org/x/sys v0.0.0-20200831180312-196b9ba8737a // indirect
)
replace (
github.com/yourAccount/yourModule/localFolder =>"./yourModule/localFolder"
github.com/yourAccount/yourModule/localFolder =>"./yourModule/localFolder"
)
Then in your main.go =>
import (
alog "github.com/yourAccount/yourModule/localFolder"
slog "github.com/yourAccount/yourModule/localFolder"
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With