解决循环模块加载的最佳方法

Best Way to Resolve Circular Module Loading

我正在尝试让两个不同的对象相互引用并对属性进行类型检查。当我这样做时,我得到 Circular module loading detected trying to precompile。谷歌搜索让我 https://docs.raku.org/language/faq#Can_I_have_circular_dependencies_between_modules?其中指出:

Note that Raku has no “1 file = 1 class” limitation, and circular dependencies within a single compilation unit (e.g., file) are possible through stubbing. Therefore another possible solution is to move classes into the same compilation unit.

如果可以避免的话,我宁愿不把两个 类 放在同一个单元中。由于没有示例,我不确定如何通过存根来完成此操作。以下是我正在尝试做的一个小例子:

Yak.rakumod

unit class Yak;

use YakStore;

has YakStore $.yak-store is rw;

YakStore.rakumod

unit class YakStore;

use Yak;

has Yak $.yak is rw;

yak.rakutest

use lib '.';

use Test;

use Yak;
use YakStore;

plan 2;

my $yak-store = YakStore.new;

my $yak = Yak.new(:$yak-store);

$yak-store.yak = $yak;

isa-ok $yak-store.yak, Yak;
isa-ok $yak.yak-store, YakStore;

是的,我知道,测试是蹩脚的,但我只是想说明问题。谢谢!

处理循环依赖的最好方法是把你的圆变成三角形——也就是说,让两个 类 相互依赖而不是(至少部分地)依赖第三个角色。

这是您提供的示例和 Shaveable 角色的样子(Yak 应该是 Shaveable,对吧?):

Shaveable.rakumod

unit role Shaveable;

Yak.rakumod

use YakStore;
use Shaveable;

unit class Yak does Shaveable;

has YakStore $.yak-store is rw;

YakStore.rakumod

use Shaveable;
unit class YakStore;

has Shaveable $.yak is rw;

经过这一更改,您的示例中的测试现在通过了。