Golang, Using a Structure or function of a main package from a sub package

huangapple go评论84阅读模式
英文:

Golang, Using a Structure or function of a main package from a sub package

问题

我正在尝试编写一个带有多个子项目的Go项目。以一个简单的示例为例,项目的结构如下:

Main
 |- package one
    |- package one.one
    |- package one.two
 |- package two

从我的主包中,我可以通过导入来使用任何子包的函数或结构体。但我的问题是,如何从任何子包中访问主包的结构体或函数。

英文:

I am trying to write a go project with several sub projects. For an simple example the project looks like this

Main
 |- package one
    |- package one.one
    |- package one.two
 |- package two

From my main package i can use any function or structure of any sub package By importing them. But My question is how can i access an struct or function of main from any sub package.

答案1

得分: 5

通过在主程序中导入“子包”。但是不要产生导入循环(在这种情况下重新组织你的代码)。

请注意,Go语言几乎没有“子包”的概念:它们都是普通的包,目录布局对导入、可用性和访问性并没有影响,包括导出的函数、类型、方法、字段、变量和常量。

但是,内部包和供应商包依赖于目录布局。

英文:

By importing the "subpackages" in main. But do not produce an import cycle (Restructure your code in this case).

Note that Go has (almost*) no notion of _sub_package: These are all plain packages and the directory layout has no influence on imports and usability/accessability of exported functions, types, methods, fields, variables and constants.

*) Internal packages and vendored packages depend on directory layout.

答案2

得分: 3

谢谢。我通过使用第三方包解决了这个问题。这样做相当简单。

英文:

Thanks. I solved this problem by using an third package. Pretty easy that way.

huangapple
  • 本文由 发表于 2015年9月3日 11:49:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/32366653.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定