如何从父目录进行相对导入?
从 meme / cmd / meme :
import../../../meme这给出了一个模棱两可的错误:
matt @ stanley: 〜/ gopath / src / bitbucket / anacrolix / meme / cmd / meme $ go get bitbucket/anacrolix/meme/cmd/meme 无法加载软件包:/ home / matt /非本地包中的gopath / src / bitbucket / anacrolix / meme / cmd / meme / main.go:8:2:本地导入../../../meme matt @ stanley:〜/ gopath / src / bitbucket / anacrolix / meme / cmd / meme $ echo $ GOPATH $ b $ / home / matt / gopath 如何从父目录本地导入?解决方案感谢您添加到您的问题。首先是答案,然后是一些解释。我通过构建你的代码,
在我的评论中,当我说去安装工程时,我错了;我应该说,去建设。
然而,关键是单独的 go build 不起作用;你必须输入 go build main.go 。这是因为go命令不允许非本地包中的本地导入。你说得对,规范在这里没有什么帮助。它狡猾地说:ImportPath的解释是依赖于实现的。当前的实施行为是通过 CL 5787055 进行设置的,后来随后是详细讨论Go-nuts。
本地是指文件系统相对路径。显然,以..开头的相对路径是本地的,所以诀窍就是获取 go 命令将main作为本地包对待。当你键入 go build 时显然没有这样做,但是当你输入 go build main.go 的时候不会这样做。
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/anacrolix/meme/cmd/meme$ go get bitbucket/anacrolix/meme/cmd/meme can't load package: /home/matt/gopath/src/bitbucket/anacrolix/meme/cmd/meme/main.go:8:2: local import "../../../meme" in non-local package matt@stanley:~/gopath/src/bitbucket/anacrolix/meme/cmd/meme$ echo $GOPATH /home/matt/gopathHow do I import locally from a parent directory?
解决方案Thanks for adding to your question. First, an answer, then some explanation. I built your code by,
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.
更多推荐
从父目录进行相对导入
发布评论