dtye7921 2014-07-02 08:34
浏览 476
已采纳

Golang中的“相互”包导入

Is it possible to do something like a "mutual" package import in Golang?

Lets say for example I have two packages, A and B with functions AFunc and BFunc, BFunc2

package A
import "B"

func AFunc() {
    //do stuff but also use
    B.BFunc()
}

-

package B
import "A"

func BFunc() {
    //do foo
}

func BFunc2() {
    //do different stuff but also use
    A.AFunc()
}

Is there a way to achieve this without using a third package as "bridge"?

Edit: To clarify the question a bit, this is of course not possible by "simply doing" it since the compiler will throw an import cycle not allowed error. The question is, is there a cleaner or more established way of working around this problem then building a "bridge package"?

  • 写回答

1条回答 默认 最新

  • doukong9316 2014-07-02 09:35
    关注

    interface should be an obvious answer: as long as both packages propose interfaces with a common set of functions, it allows for:

    • packageB to use functions from A (import A)
    • packageA to call functions from B without having to import B: all it need to be passed B instances which implements an interface defined in A: those instances will be views as A object.
      In that sense, packageA ignores the existence of packageB.

    This is also illustrated in the comment of "Cyclic dependencies and interfaces in golang".

    If package X accepts/stores/calls methods on/returns types defined package Y, but doesn't actually access Y's (non-method) functions or variables directly, X can use an interface that the type in Y satisfies rather than actually importing Y.

    avoiding dependencies with interfaces in general, you can see how, say, the io module doesn't depend on os for the File class even though its functions can work on Files. (It just defines io.Writer, etc., and *os.File satisfies those interfaces.)

    For instance, io accepts a 'Writer' in its Copy() function (which can be a File or another else knowing how to write), and ignores completely os(.File)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?