从父目录相对导入

编程入门 行业动态 更新时间:2024-10-28 08:28:08
本文介绍了从父目录相对导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何从父目录进行相对导入?

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/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/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 or go 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.

    更多推荐

    从父目录相对导入

    本文发布于:2023-11-24 03:08:11,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1623753.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:目录

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!