"相互"软件包导入Golang [英] "Mutual" package import in Golang
问题描述
比方说,我有两个包A和B,包含函数AFunc和BFunc,BFunc2
包A
导入B
func AFunc(){
//做的东西,但也使用
B.BFunc()
}
$ b func BFunc( ){
// do foo
}
func BFunc2(){
//做不同的事情,但也使用
A.AFunc()
}
有没有办法在不使用第三个包作为桥的情况下实现这一点?
编辑:
为了澄清这个问题,这当然是不可能的,因为编译器会将导入周期不允许
错误。问题是,是否有一种更清洁或更为成熟的方法来解决这个问题,然后构建一个桥包? 解决方案
界面应该是一个明显的答案:只要这两个软件包都提供了一个通用集合的接口它允许:
packageB
使用<$ c中的函数$ c> A ( import A
)
packageA
> A
中定义的接口的实例:这些实例将视图为 A
object。
在这个意义上, packageA
忽略 packageB
的存在。 li>
这也在
$ b
$ b $ / questions / 20380333 / cyclic-dependencies-and-interface-in-golang#comment30438237_20380333> golang中的循环依赖和接口 b如果包
X
接受/ stores / calls方法在/ returns类型中定义包Y
,但doesn' t直接访问Y
的(非方法)函数或变量,X
可以使用一个类型的接口在Y
中满足而不是实际导入Y
。
避免了一般的接口依赖,你可以看到
io
模块不依赖os
为 File class ,即使它的函数可以在Files
上工作。 (它只是定义了io.Writer
等,以及* os.File $ c $ )
例如, io
在其 Copy()
中接受'Writer' >函数(可以是File或其他知道如何编写的函数),并且完全忽略 os
(。File)
Is it possible to do something like a "mutual" package import in Golang?
Lets say for example I have two packages, A and B with functions AFunc and BFunc, BFunc2
package A
import "B"
func AFunc() {
//do stuff but also use
B.BFunc()
}
-
package B
import "A"
func BFunc() {
//do foo
}
func BFunc2() {
//do different stuff but also use
A.AFunc()
}
Is there a way to achieve this without using a third package as "bridge"?
Edit:
To clarify the question a bit, this is of course not possible by "simply doing" it since the compiler will throw an import cycle not allowed
error. The question is, is there a cleaner or more established way of working around this problem then building a "bridge package"?
interface should be an obvious answer: as long as both packages propose interfaces with a common set of functions, it allows for:
packageB
to use functions fromA
(import A
)packageA
to call functions fromB
without having toimport B
: all it need to be passedB
instances which implements an interface defined inA
: those instances will be views asA
object.
In that sense,packageA
ignores the existence ofpackageB
.
This is also illustrated in the comment of "Cyclic dependencies and interfaces in golang".
If package
X
accepts/stores/calls methods on/returns types defined packageY
, but doesn't actually accessY
's (non-method) functions or variables directly,X
can use an interface that the type inY
satisfies rather than actually importingY
.avoiding dependencies with interfaces in general, you can see how, say, the
io
module doesn't depend onos
for the File class even though its functions can work onFiles
. (It just definesio.Writer
, etc., and*os.File
satisfies those interfaces.)
For instance, io
accepts a 'Writer' in its Copy()
function (which can be a File or another else knowing how to write), and ignores completely os
(.File)
这篇关于"相互"软件包导入Golang的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!