Home > Software design >  Golang accessing parent package values in child package
Golang accessing parent package values in child package

Time:08-24

Hello i think i am running into an interface/struct problem. I know go doesn't support inheritance and im kind of stomp on figuring this import cycle not allowed bug.

In my actual code I have defined a struct inside pkg A that I want to access in pkg C . Im seeing i should use interfaces to accomplish this but I don't know how I should do this. For example I have something like pkg A is the parent pkg B is the child pkg C` is another child


import pkg B

B.test1() // accessing method from pkg B


pkg B

import pkg C
import pkg A

C.test2() // accessing method from pkg C

pkg C
import pkg A
// This results in a import cycle error
A.Field1 // Trying to access a struct value from the parent package```

CodePudding user response:

The dependency graph described by package imports must be acyclic, hence the "import cycle not allowed" error message you're encountering.

If, for instance, package Alpha imports package Bravo and package Bravo imports package Charlie, package Charlie can't import package Alpha (or Bravo for that matter) because that would introduce a cycle into the dependency graph.

The shared dependency(ies) need to be refactored into another package so as to eliminate the cycle. In my above example, you might refactor package Alpha and extract the bits that both it and package Charlie need into a new package Delta that gets imported by both Alpha and Charlie.

  • Related