gorm many2many 导致 [gopls] import cycle not allowed

发布时间: 2022-10-11 13:18:35 作者: 大象笔记

今天第一次遇到 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.

参考

我是一名山东烟台的开发者,联系作者