本文介绍了"相互"软件包导入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 > > B > 所有需要传递的函数<$ c $> c> B 实现了在 A 中定义的接口的实例:这些实例将视图为 A object。
在这个意义上, packageA 忽略 packageB 的存在。 li>
这也在(可以是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 from A (import A)
- packageA to call functions from B without having to import B: all it need to be passed B instances which implements an interface defined in A: those instances will be views as A object.
In that sense, packageA ignores the existence of packageB.
This is also illustrated in the comment of "Cyclic dependencies and interfaces in golang".
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!