循环依赖本质上一次错误的设计,在go
里面,直接把它作为了一个编译时的错误。
package 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()
}
package 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()
}
import cycle not allowed
package my-test/importcicle
imports my-test/importcicle/a
imports my-test/importcicle/b
imports my-test/importcicle/a
package x
type ADoSomethingIntf interface {
DoSomethingWithA()
}
import (
"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()
}
import (
"my-test/importcicle/a"
"my-test/importcicle/b"
)
func doSomethingWithY() {
o := &a.A{}
b.InvokeSomethingFromA(o)
}
不错
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit