Go里面的循环依赖

in golang •  3 years ago  (edited)

循环依赖本质上一次错误的设计,在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)
}

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

不错