Preface
golang does not allow looping of import package. If an import cycle is detected, an error will be reported during compilation. Usually, the import cycle is due to design errors or package planning problems.
The following example is as an example, package a depends on package b, and colleague package b depends on package a
package a import ( "fmt" "/mantishK/dep/b" ) type A struct { } func (a A) PrintA() { (a) } func NewA() *A { a := new(A) return a } func RequireB() { o := () () }
package b:
package b import ( "fmt" "/mantishK/dep/a" ) type B struct { } func (b B) PrintB() { (b) } func NewB() *B { b := new(B) return b } func RequireA() { o := () () }
An error will be reported during compilation:
import cycle not allowed
package /mantishK/dep/a
imports /mantishK/dep/b
imports /mantishK/dep/a
The problem now is:
A depends on B
B depends on A
So how to avoid it?
Introduce package i, introduce interface
package i type Aprinter interface { PrintA() }
Let package b import package i
package b import ( "fmt" "/mantishK/dep/i" ) func RequireA(o ) { () }
Introduce package c
package c import ( "/mantishK/dep/a" "/mantishK/dep/b" ) func PrintC() { o := () (o) }
Now the dependency relationship is as follows:
A depends on B
B depends on I
C depends on A and B
Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.