我有一个特征和一个实现该特征的结构(一个特征对象)。我想在堆上分配我的特征对象并让其他结构引用它们。
框字段
trait Material {}
struct Iron {}
impl Material for Iron {}
// It works, but takes ownership of boxes.
struct Sphere {
radius: f64,
material: Box<dyn Material>,
}
这段代码有效,但我不能让两个球体共享相同的Material
,因为Box
拥有材料,球体拥有它的Box
场。
参考字段
我的下一个尝试是使用普通参考而不是Box
:
struct Sphere<'a> {
radius: f64,
material: &'a dyn Material,
}
这也有效,但据我了解,我Material
的 s 将分配在堆栈而不是堆上。如果Material
值真的很大而且我宁愿把它放在堆上怎么办?这导致我采用下一种无法编译的方法:
引用框
struct Sphere<'a> {
radius: f64,
material: &'a Box<dyn Material>,
}
fn main() {
let m1 = &Box::new(Iron {});
let s1 = Sphere {
radius: 1.0,
material: m1,
};
assert_eq!(s1.radius, 1.0);
}
这给了我以下错误:
error[E0308]: mismatched types
--> src/main.rs:16:19
|
16 | material: m1,
| ^^ expected trait Material, found struct `Iron`
|
= note: expected type `&std::boxed::Box<(dyn Material + 'static)>`
found type `&std::boxed::Box<Iron>`
我不太确定'static
该类型的来源,并且看起来它混淆了类型检查器。否则dyn Material
,Iron
据我所知可以统一。