Search code examples
importgorelative-path

Relative import from parent directory


How does one do a relative import from a parent directory?

From meme/cmd/meme:

import "../../../meme"

This gives an ambiguous error:

matt@stanley:~/gopath/src/bitbucket.org/anacrolix/meme/cmd/meme$ go get bitbucket.org/anacrolix/meme/cmd/meme

can't load package: /home/matt/gopath/src/bitbucket.org/anacrolix/meme/cmd/meme/main.go:8:2: local import "../../../meme" in non-local package

matt@stanley:~/gopath/src/bitbucket.org/anacrolix/meme/cmd/meme$ echo $GOPATH

/home/matt/gopath

How do I import locally from a parent directory?


Solution

  • Thanks for adding to your question. First, an answer, then some explanation. I built your code by,

    1. go get, just as you had it. (I ignored the error messages.)
    2. setting the import line in main.go back to "../../../meme", as you wanted to do.
    3. (commenting out a little bit of code containing an unused variable.)
    4. then in the meme/cmd/meme directory, either go run main.go or go build main.go worked.

    I was wrong in my comment earlier when I said go install works; I should have said go build.

    The key however is that go build alone does not work; you must type go build main.go. This is because the go command does not allow "local imports in non-local packages." You are right that spec is of little help here. It weasels out saying, "The interpretation of the ImportPath is implementation-dependent." The current implementation behavior was set with CL 5787055, which was subsequently debated at length on Go-nuts.

    "Local" means indicated with a file system relative path. Obviously a relative path starting with .. is local, so the trick is just getting the go command to treat main as a local package as well. It apparently doesn't do this when you type go build, but does when you type go build main.go.