从父目录相对导入 [英] Relative import from parent directory
问题描述
如何从父目录进行相对导入?
How does one do a relative import from a parent directory?
来自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?
推荐答案
感谢您添加问题.首先是一个答案,然后是一些解释.我构建了你的代码,
Thanks for adding to your question. First, an answer, then some explanation. I built your code by,
- 去拿,就像你曾经拥有的那样.(我忽略了错误消息.)
- 将
main.go
中的导入行设置回../../../meme",如您所愿. - (注释掉一些包含未使用变量的代码.)
- 然后在 meme/cmd/meme 目录中,
go run main.go
或go build main.go
工作.
- go get, just as you had it. (I ignored the error messages.)
- setting the import line in
main.go
back to "../../../meme", as you wanted to do. - (commenting out a little bit of code containing an unused variable.)
- then in the meme/cmd/meme directory, either
go run main.go
orgo build main.go
worked.
当我说 go install 有效时,我之前的评论是错误的;我应该说去构建.
I was wrong in my comment earlier when I said go install works; I should have said go build.
然而,关键是 go build
本身是行不通的;你必须输入 go build main.go
.这是因为 go 命令不允许在非本地包中进行本地导入".你是对的,规范在这里没什么帮助.它狡猾地说,ImportPath 的解释是依赖于实现的."当前的实现行为是使用 CL 5787055 设置的,随后是 对 Go-nuts 进行了详细的辩论.
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.
本地"表示用文件系统相对路径表示.显然以 .. 开头的相对路径是本地的,所以诀窍是让 go
命令也将 main 视为本地包.当您键入 go build
时,它显然不会这样做,但是当您键入 go build main.go
时会这样做.
"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
.
这篇关于从父目录相对导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!