转到:以非本地包形式进行本地导入

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() {

}

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

If you just want to share code between separate files and not separate packages, here's how to do it:

You don't need to import, you just have to put the source files in the same directory and specify the same package name at the top of each file, and then you can access all the public (Uppercase) functions and types, by referencing them directly, that is, SomeFunction() and not somepackage.SomeFunction()