gpt4 book ai didi

rust - 如何创建具有特征作为参数的setter

转载 作者:行者123 更新时间:2023-12-04 07:26:29 24 4
gpt4 key购买 nike

刚开始使用 Rust。想创建一个接受 trait 作为参数的 setter。
说明想法

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 中吗? ?

最佳答案

鉴于以下 Engine指定 start() 的特征作为方法而不是关联函数:

pub trait Engine {
fn start(&mut self) -> bool;
}
您的 DummyEngine不打算实现 Engine特征。你可以只实现 EngineDummyEngine :
struct DummyEngine;

impl Engine for DummyEngine {
fn start(&mut self) -> bool { false }
}
这种方法——即使用虚拟对象——将对应于 Null Object Pattern .但是,你可以去 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()按值(value)。 Box拥有 Engine ,它将被移入 engine field 。也就是说, Box传递的参数移动到参数 engine并且,这反过来又移入 engine领域 Car .

Car::new()不带任何参数,你可能想要实现 Default Car 的特征还有:
impl Default for Car {
fn default() -> Self {
Car::new()
}
}

关于rust - 如何创建具有特征作为参数的setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68192127/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com