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".
For instance,
io
accepts a 'Writer' in itsCopy()
function (which can be a File or another else knowing how to write), and ignores completelyos
(.File)