刚从铁锈开始。想要创建一个将接受特征作为param的设置者。阐释思想
pub trait Engine {
fn start() -> bool;
}
struct Car {
engine: Box<dyn Engine>,
}
impl Car {
pub fn new() -> Self {
let engine = Box::new(DummyEngine {});
Self {
engine,
}
}
pub fn set_engine(&mut self, engine: &dyn Engine) {
self.engine = Box::new(engine);
}
}setter代码抱怨:
the trait bound `&dyn Engine: Engine` is not satisfied
required for the cast to the object type `dyn Engine` rustcE0277此外,如何避免虚拟默认引擎?假设一辆车不需要引擎。它应该包装在Option中吗?
发布于 2021-06-30 09:53:33
给定以下Engine特性,将start()指定为方法而不是关联函数:
pub trait Engine {
fn start(&mut self) -> bool;
}您的DummyEngine不打算实现Engine特性。您只需为Engine实现DummyEngine
struct DummyEngine;
impl Engine for DummyEngine {
fn start(&mut self) -> bool { false }
}这种方法--即使用虚拟对象--将对应于空对象模式。但是,您可以按照您的建议选择Option,并将Car定义为:
struct Car {
engine: Option<Box<dyn Engine>>,
}这样,您就可以将new()和set_engine()实现为:
impl Car {
pub fn new() -> Self {
Car {
engine: None,
}
}
pub fn set_engine(&mut self, engine: Box<dyn Engine>) {
self.engine = Some(engine);
}
}您将按值将Box<dyn Engine>传递给set_engine()。Box拥有Engine,它将被移动到engine字段中。也就是说,传递的Box参数被移到参数engine中,然后移动到Car的engine字段中。
由于Car::new()不带任何参数,所以您可能也希望为Car实现Default特性:
impl Default for Car {
fn default() -> Self {
Car::new()
}
}https://stackoverflow.com/questions/68192127
复制相似问题