gorm many2many 导致 [gopls] import cycle not allowed

更新日期: 2022-10-11 阅读次数: 1898 字数: 213 分类: golang

今天第一次遇到 go 的循环引用问题:

[gopls] import cycle not allowed

起因

新项目使用了新的包结构,每个 model 及对应 controller 放到独立的 package 中。 而不是两个大 models 目录,controllers 目录。

恰好一个 gorm many2many 关系导致两个 package 相互依赖,例如,文章及标签。

article 和 tag 这俩个 model 引起了 import cycle。

go 为何要禁止 import cycle

提升编译速度。

解决办法

Packages are compilation units, nothing more. If you can't compile two types in different because they refer to each other, simply put them in one package.

  • 整理思路:尽量少改代码
  • 只将 tag package 中的 model.go 移动到 models package: 如此,还带来一个好处,用 models.Tag 可以避免 tag 包名与变量名 tag 冲突。

参考

  • https://jogendra.dev/import-cycles-in-golang-and-how-to-deal-with-them
  • https://www.reddit.com/r/golang/comments/r2dp2e/how_to_avoid_import_cycle_not_allowed_when/

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式