go什么是循环依赖呢?
ABABabABBA没有代码bb什么,直接上代码
apackage a
import (
"fmt"
"my-test/importcicle/b"
)
type A struct {
}
func (a A) DoSomethingWithA() {
fmt.Println(a)
}
func CreateA() *A {
a := &A{}
return a
}
func invokeSomethingFromB() {
o := b.CreateB()
o.DoSomethingWithB()
}
bpackage b
import (
"fmt"
"my-test/importcicle/a"
)
type B struct {
}
func (b B) DoSomethingWithB() {
fmt.Println(b)
}
func CreateB() *B {
b := &B{}
return b
}
func invokeSomethingFromA() {
o := a.CreateA()
o.DoSomethingWithA()
}
正如上面的代码,A需要B,B也需要A,这样就导致了循环导入或者说循环依赖。当你要编译这段代码时,会报错:
import cycle not allowed
package my-test/importcicle
imports my-test/importcicle/a
imports my-test/importcicle/b
imports my-test/importcicle/a
那怎么解决这种循环依赖,平时写代码,一时兴起,不小心写个循环依赖也是常有的事
xinterfacepackage x
type ADoSomethingIntf interface {
DoSomethingWithA()
}
xaimport (
"fmt"
"my-test/importcicle/x"
)
type B struct {
}
func (b B) DoSomethingWithB() {
fmt.Println(b)
}
func CreateB() *B {
b := &B{}
return b
}
// 注意 这里稍微做了些调整
func invokeSomethingFromA(o x.ADoSomethingIntf) {
o.DoSomethingWithA()
}
AyyabAbimport (
"my-test/importcicle/a"
"my-test/importcicle/b"
)
func doSomethingWithY() {
o := &a.A{}
b.InvokeSomethingFromA(o)
}
这就是我解决循环依赖的方式,总结就是:
ABBXYAB因此没有循环依赖
有什么好的方法,可以发表在评论区,互相学习