我对Rust还很陌生,我打算实现一个 struct ,该 struct 可以具有不同的 struct ,该 struct 将一个共同的特征实现为一个字段
在使用垃圾收集器的传统编程语言中,我会这样实现它:
pub struct MemoryMapper {
regions: Vec<Region>,
}
trait MemoryMappable: Sized {
}
pub struct Region {
device: dyn MemoryMappable,
start: u32,
end: u32,
remap: bool
}
但在这里,我有以下编译错误:
the size for values of type `(dyn MemoryMappable + 'static)` cannot be known at compilation time
the trait `Sized` is not implemented for `(dyn MemoryMappable + 'static)`
only the last field of a struct may have a dynamically sized type
change the field's type to have a statically known size
我曾try 将Size设置为MemoyMappable的一个附加特征,但它仍然让我在以下代码中遇到问题:
pub fn map(&mut self, device: dyn MemoryMappable, start: u32, end: u32, remap: bool) -> &Region {
self.regions.insert(0, Region{device, start, end, remap});
return self.regions.get(0).unwrap();
}
the trait `MemoryMappable` cannot be made into an object
`MemoryMappable` cannot be made into an object
因为从Rust documentation about object safety
尺码不能是一种超级特征.换句话说,它不能要求自己的尺寸.
在这一点上我不知道该怎么做.