我有两个需要相互引用的结构。由于其他原因,这些结构需要同时绕过借用检查器。所以我有个包装器来绕过检查器。现在,我试图让每个结构都有第二个结构的泛型类型。
这是一个玩具例子:
use d2simrs::util::internalref::InternalRef;
pub trait Layer3Trait {
fn foo() {
println!("TraitA::foo()");
}
}
pub trait Layer2Trait {
fn bar() {
println!("TraitB::foo()");
}
}
pub struct SimpleLayer2<Layer3T>
where Layer3T: Layer3Trait
{
pub layer3: InternalRef<Layer3T>,
}
pub struct SimpleLayer3<Layer2T>
where Layer2T: Layer2Trait
{
pub layer2: InternalRef<Layer2T>,
}
pub type Layer2 = SimpleLayer2<Layer3>;
pub type Layer2Ref = InternalRef<Layer2>;
pub type Layer3 = SimpleLayer3<SimpleLayer2<Layer3>>;
pub type Layer3Ref = InternalRef<Layer3>;InternalRef的代码是这里
我就能得到
|
30 | pub type Layer3 = SimpleLayer3<SimpleLayer2<Layer3>>;
| ^^^^^^
|
= note: ...which again requires computing type of `example2::Layer3`, completing the cycle
note: cycle used when computing type of `example2::Layer2`
--> examples/network/bypass_borrow/example2.rs:27:32
|
27 | pub type Layer2 = SimpleLayer2<Layer3>;
| ^^^^^^我能不能重新定义一些东西,这样SimpleLayer2和SimpleLayer3就可以相互引用了。
发布于 2021-10-11 19:30:15
锈病不支持循环的泛型类型。如果你有:
pub type Layer2 = SimpleLayer2<Layer3>;
pub type Layer3 = SimpleLayer3<Layer2>;那么具体类型的Layer3将是:
SimpleLayer3<SimpleLayer2<SimpleLayer3<SimpleLayer2<SimpleLayer3<SimpleLayer2<SimpleLayer3<SimpleLayer2<SimpleLayer3<SimpleLayer2<SimpleLayer3<...>>>>>>>这是不允许的。
正如评论中提到的那样,如果您的设计是传家宝式的,没有循环依赖,这将是理想的,因为它显然可以避免此类问题。但是,如果这不合适,解决这一问题的标准方法是使用Rc/Arc和特性对象,这也将避免内部*mut T包装器(如果需要可变时使用RefCell/RwLock ):
use std::rc::{Rc, Weak};
pub struct SimpleLayer2 {
pub layer3: Weak<RefCell<dyn Layer3>>,
}
pub struct SimpleLayer3 {
pub layer2: Rc<RefCell<dyn Layer2>>,
}关于其他潜在想法,请参阅以下其他问题:
https://stackoverflow.com/questions/69433749
复制相似问题