3

I have A.go file with a method as follows.

func pInfoEx(reqCtx B.RequestContext) {
    fmt.Println(reqCtx.p);
}

For this RequestContext argument in the pInfoEx function I have to import the B.go file which is in another package.

type RequestContext interface {
    p() string
}

But B.go imports C.go which inturn imports A.go creating cyclic dependency. How can I go about resolving this cyclic dependency without moving go files to the same package?

I have gone through Cyclic dependencies and interfaces in Golang post, but here the method has an argument which cannot be changed.

BigDataLearner
  • 1,388
  • 4
  • 19
  • 40
  • if you cannot change the argument `reqCtx B.RequestContext` to an interface type to avoid the cyclic dependency then change the **C.go** type that **B.go** depends on, if you cannot do that either then change the **A.go** type that **C.go** depends on, and so on... And if all of your packages require concrete types that you cannot change to interface then your only option left is to restructure you packages in such a way that there is no more cyclic dependency. – mkopriva Nov 24 '17 at 20:21

1 Answers1

1

One way is to move all data type and interface definitions to separate package, so all will be dependent on it, but the package does not depend on any other. This can be a special package schema in root folder of the project. Or even top project itself.

Eugene Lisitsky
  • 12,113
  • 5
  • 38
  • 59