Three structures are there: A(package a)
,B(package b)
,C(package c)
.
B
wants to use functionality of C
and C
wants to use functionality of B
.
A
has both B
and C
instances, so that B
can access functionality of C
via A
and vice versa.
I used an interface Ageter
declared in another package i
which has function declaration as GetA() *a.A
Now I am using this interface Ageter
in B
and C
through which I get instance of A
and access functionality of C
and B
respectively.
package a
import (
"fmt"
"basics/importCycleIssue/issueFix/b"
"basics/importCycleIssue/issueFix/c"
)
type A struct {
B *b.B
C *c.C
}
var a = NewA()
func NewA() *A {
a := &A{}
a.B = b.NewB(a)
a.C = c.NewC(a)
return a
}
func GetA() *A{
return a
}
---------------------------------------------------
package b
import (
"fmt"
"basics/importCycleIssue/issueFix/i"
)
type B struct {
o i.Ageter
}
func NewB(o i.Ageter) *B {
b := &B{o: o}
return b
}
func (b *B) UseC() {
fmt.Println("need to use C:",b.o.GetA().C)
}
----------------------------------------------------
package c
import (
"fmt"
"basics/importCycleIssue/issueFix/i"
)
type C struct {
o i.Ageter
}
func NewC(o i.Ageter) *C {
c := &C{o: o}
return c
}
func (c *C) UseB() {
fmt.Println("need to use B:",c.o.GetA().B)
}
----------------------------------------------------
package i
import (
"basics/importCycleIssue/issueFix/a"
)
type Aprinter interface {
PrintA()
}
type Ageter interface {
GetA() *a.A
}
---------------------------------------------------
package main
import (
"basics/importCycleIssue/issueFix/a"
)
func main() {
o := a.NewA()
o.B.UseC()
o.C.UseB()
}
I should be able to use functionality of B
in C
and vice versa.
While building the code I am getting import cycle not allowed
error.
import cycle not allowed
package main
imports basics/importCycleIssue/issueFix/a
imports basics/importCycleIssue/issueFix/b
imports basics/importCycleIssue/issueFix/i
imports basics/importCycleIssue/issueFix/a
Can anyone tell me how to fix this problem?
Thanks.