如何使用“内部"包? [英] How to use "internal" packages?

查看:65
本文介绍了如何使用“内部"包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了解如何使用内部"包组织代码.让我展示一下我的结构:

I try understand how to organize go code using "internal" packages. Let me show what the structure I have:

project/
  internal/
    foo/
      foo.go # package foo
    bar/
      bar.go # package bar
  main.go

# here is the code from main.go
package main

import (
  "project/internal/foo"
  "project/internal/bar"
)

project/在GOPATH树之外.无论我尝试从main.go导入的任何路径都行不通,唯一可以正常工作的情况是import "./internal/foo|bar".我认为我做错了什么,或者总体上弄错了内部"包装想法.任何人都可以让事情变得更清楚吗?

project/ is outside from GOPATH tree. Whatever path I try to import from main.go nothing works, the only case working fine is import "./internal/foo|bar". I think I do something wrong or get "internal" package idea wrong in general. Could anybody make things clearer, please?

更新

上面的示例是正确的,我唯一需要的是将project/文件夹放置在下.因此,如果仅从project/子树而不是从外部导入,则像project/internal/foo|bar这样的导入路径是可行的.

The example above is correct the only what I need was to place project/ folder under $GOPATH/src. So the thing is import path like the project/internal/foo|bar is workable if we only import it from project/ subtree and not from the outside.

推荐答案

必须将软件包放在您的$GOPATH中才能导入.您使用import "./internal/foo|bar"给出的示例可以正常工作,因为它可以进行本地导入. internal只是这样做,因此与您的internal目录没有共享公共根目录的代码无法导入internal中的软件包.

The packages have to be located in your $GOPATH in order to be imported. The example you gave with import "./internal/foo|bar" works because it does a local-import. internal only makes it so code that doesn't share a common root directory to your internal directory can't import the packages within internal.

如果将所有这些内容放入gopath中,然后尝试从不同的位置(如OuterFolder/project2/main.go)导入,其中OuterFolder包含projectproject2,则import "../../project/internal/foo"将失败.由于不满足此条件,它也可能会以import "foo"或您尝试的任何其他方式失败;

If you put all this in your gopath then tried to import from a different location like OuterFolder/project2/main.go where OuterFolder contains both project and project2 then import "../../project/internal/foo" would fail. It would also fail as import "foo" or any other way your tried due to not satisfying this condition;

如果存在以下情况,则不允许导入包含内部"元素的路径 导入代码位于以父代为根的树之外 内部"目录.

An import of a path containing the element "internal" is disallowed if the importing code is outside the tree rooted at the parent of the "internal" directory.

现在,如果您具有路径$GOPATH/src/project,则可以从$GOPATH/src/project/main.go内部执行import "foo"import "bar",导入将成功.但是,未包含在project下的内容将无法导入foobar.

Now if you had the path $GOPATH/src/project then you could do import "foo" and import "bar" from within $GOPATH/src/project/main.go and the import would succeed. Things that are not contained underneath project however would not be able to import foo or bar.

这篇关于如何使用“内部"包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆