Golang does not allow circular import package, if the import cycle detected, will be wrong in the compile times, usually import cycle is due to design errors or package planning problems.
In the example below, package a relies on package B, colleague Package B relies on package a
Package A
Import (
"FMT"
"Github.com/mantishk/dep/b"
)
Type A struct {
}
Func (a) PrintA () {
Fmt. Println (a)
}
Func Newa () *a {
A: = new (a)
Return a
}
Func Requireb () {
o: = B.NEWB ()
O.PRINTB ()
}
Package B:
Package B
Import (
"FMT"
"GITHUB.COM/MANTISHK/DEP/A"
)
Type B struct {
}
Func (b) Printb () {
Fmt. Println (b)
}
Func newb () *b {
B: = new (b)
Return b
}
Func Requirea () {
o: = A.newa ()
O.printa ()
}
Would be wrong in compiling the Times:
Import Cycle not allowed
Package github.com/mantishk/dep/a
Imports Github.com/mantishk/dep/b
Imports GITHUB.COM/MANTISHK/DEP/A
Now the question is:
A depends on B
B depends on A
So how to avoid it?
Introducing package I and introducing interface
Package I
Type Aprinter Interface {
PrintA ()
}
Let package B Import Package I
Package B
Import (
"FMT"
"Github.com/mantishk/dep/i"
)
Func Requirea (o i.aprinter) {
O.printa ()
}
Introduction of Package C
Package C
Import (
"GITHUB.COM/MANTISHK/DEP/A"
"Github.com/mantishk/dep/b"
)
Func Printc () {
o: = A.newa ()
B.requirea (o)
}
Now the dependencies are as follows:
A depends on B
B depends on I
C depends on A and B