2018-05-04 02:44
浏览 57


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)

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?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dovzrfr0506 2018-05-04 02:56

    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.

    打赏 评论
  • duanpa1980 2018-05-04 05:25

    Two ways to go about it:

    1. Create a new package which contains functions common to both, then import that package in both packages.

    2. Consider whether all these belong to the same package instead of two different packages.

    打赏 评论

相关推荐 更多相似问题