dtf24224 2012-05-21 14:53
浏览 91
已采纳

从父目录的相对导入

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?

  • 写回答

3条回答 默认 最新

  • dou448172583 2012-05-22 19:29
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?