Go: local import in non-local package

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

  • https://groups.google.com/forum/#!topic/golang-nuts/1XqcS8DuaNc/discussion
  • https://github.com/golang/go/issues/12502
  • https://github.com/golang/go/issues/3515#issuecomment-66066361

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"
)

you can bypass this using the vendor feature
change import "./greeting" to import "greeting"
create the vendor directory mkdir vendor and create a symlink ln -s ../greeting vendor/greeting