I am quite new to Go and I fell on an import cycle that I'm not sure how I should solve. I have multiple class that implements a specific interface. I also have another class that will return the interface corresponding to the specific class id. Problem arrives when any specific class needs to use my other class. Here's an exemple:
package examplepkg
import otherpkg
type ExampleClass {}
func NewExampleClass() *ExampleClass {
return &ExampleClass{}
}
func (ex *ExampleClass) ExampleMethod() { // Implements ExampleInterface
var id int // Read from some external source
theinterface := otherpkg.GetExampleInterface(id)
theinterface.ExampleMethod()
}
And the function in another package:
package otherpkg
import examplepkg
func GetExampleInterface(id int) *ExampleInterface {
switch id {
case 3000: return examplepkg.NewExampleClass()
}
}
If you need a bit of context, I'm reading some data from a source that I didn't create, which encapsulate some kind of data types using the ids. Example will be: id somedata id2 somedata2. And using the specific id, I can call the method to get the good type of data and the good size. They can be nested, that's why I'm using the same method ExampleMethod().
Can anyone help me to understand this problem clearly in Go?
You are creating a package examplepkg
which imports otherpkg
, when the compiler reads this file, it will first try to solve the imports before actually running the code inside examplepkg
.
Problem is your package otherpkg
is importing examplepkg
and like I said previously, it will first try to solve the imports. So, the compiler will go back to examplepkg
and try to solve the import, but it will lead it again to otherpkg
.
This results in the import cycle you are facing. One solution to this problem is to create a new package where you declare your type ExampleClass
and declare func NewExampleClass
. Then have examplepkg
and otherpkg
to import from this newly created package, breaking the import cycle you are facing right now.