是否可以在 Golang 中执行类似“相互”包导入的操作?
比方说我有两个包,A 和 B,具有函数 AFunc 和 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()
}
有没有办法在不使用第三个包作为“桥梁”的情况下实现这一点?
编辑:
为了稍微澄清一下这个问题,这当然不可能通过“简单地做”它来实现,因为编译器会抛出一个 import cycle not allowed
错误。问题是,是否有更简洁或更成熟的方法来解决此问题然后构建“桥包”?
最佳答案
interface应该是一个显而易见的答案:只要两个包都提出具有一组通用功能的接口(interface),它就允许:
packageB
使用来自A
的函数(import A
)packageA
从B
调用函数而无需import B
:所有需要传递给B
实现A
中定义的接口(interface)的实例:这些实例将被视为A
对象。
从这个意义上讲,packageA
忽略了packageB
的存在。
这在“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.)
例如,io
在其 Copy()
function 中接受一个 'Writer' (可以是文件或其他知道如何写的文件),并完全忽略 os
(.File)
关于import - "Mutual"Golang 包导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24526484/