英文:
"Mutual" package import in Golang
问题
在Golang中,是否可以实现类似于“相互”包导入的功能?
假设我有两个包,A和B,其中包含函数AFunc和BFunc、BFunc2。
package A
import "B"
func AFunc() {
//做一些事情,同时使用B.BFunc()
}
package B
import "A"
func BFunc() {
//做一些事情
}
func BFunc2() {
//做一些不同的事情,同时使用A.AFunc()
}
是否有一种方法可以在不使用第三个包作为“桥接”的情况下实现这一点?
编辑:
为了澄清问题,当然不能通过“简单地执行”来实现,因为编译器会抛出“不允许循环导入”错误。问题是,是否有一种更简洁或更成熟的方法来解决这个问题,而不是构建一个“桥接包”?
英文:
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"?
答案1
得分: 11
interface 应该是一个明显的答案:只要两个包都提供了具有共同函数集的接口,就可以实现以下功能:
packageB
可以使用A
中的函数(import A
)packageA
可以调用B
中的函数,而无需import B
:只需传递实现了A
中定义的接口的B
实例即可,这些实例将被视为A
对象。
在这个意义上,packageA
忽略了packageB
的存在。
这也可以在“Cyclic dependencies and interfaces in golang”的评论中找到。
> 如果包 X
在其方法上接受/存储/调用/返回由包 Y
定义的类型,但实际上并不直接访问 Y
的(非方法)函数或变量,X
可以使用 Y
中的类型满足的接口,而不是实际导入 Y
。
>
> 通过使用接口来避免依赖关系,你可以看到,例如,io
模块 并不依赖于 os
的 File 类,即使它的函数可以在 Files
上工作。(它只定义了 io.Writer
等,而 *os.File
满足这些接口。)
例如,io
在其 Copy()
函数 中接受一个 Writer
(可以是 File 或其他任何知道如何写入的对象),并完全忽略了 os
(.File)
英文:
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 package Y
, but doesn't actually access Y
's (non-method) functions or variables directly, X
can use an interface that the type in Y
satisfies rather than actually importing Y
.
>
> avoiding dependencies with interfaces in general, you can see how, say, the io
module doesn't depend on os
for the File class even though its functions can work on Files
. (It just defines io.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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论