dtef9322 2018-10-16 07:37
浏览 281
已采纳

包源之间的循环依赖关系

Let's say you have a package mypack with two source files mypack/a.go and mypack/b.go. Both of those source files depend on each another but the Go compiler doesn't complain. If you split that package into two, apack/a.go and bpack/b.go, the Go compiler will say import cycle not allowed.

My understanding of how package dependencies are handled is that the compiler will construct a graph of the imports. The graph is analyzed and somehow (I would love to learn about the algorithm that does this!) the order of compilation calculated. The order cannot be calculated if there is a cycle in the graph so the compiler complains.

What I don't understand is how the Go compiler is able to resolve dependencies between sources of a package but not able to resolve dependencies between packages. If the two sources depend on each other then you have to do some crazy acrobatics and compile them both at the same time somehow.

Could someone clear this up for me?

  • 写回答

2条回答 默认 最新

  • doumu6997 2018-10-16 08:13
    关注

    [...] how the Go compiler is able to resolve dependencies between sources of a package but not able to resolve dependencies between packages. If the two sources depend on each other then you have to do some crazy acrobatics and compile them both at the same time somehow.

    The question is based on wrong assumptions on how Go code is structured and compiled: A source file does not have a dependency by definition. A package has dependencies (all imports from all its source files). Dependencies are packages (not source files). To compile a package all dependencies have to be available before compilation starts.

    You really must stop thinking in terms of source files. Source files have (almost) no meaning in how Go code is compiled. A package's source may consist of one or several source files and this is basically the only point where source files enter compiling Go code. Everything relevant revolves around packages and packages only: You compile packages, you import packages, etc.

    (Just for completeness: Build tags work on source level and package initialization can depend on source code organization and by manual invoking gc you can do more than through the go tool.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。