以下是大致来自 Rust 书籍第17.2章的特质对象示例。对于我的用例,我想在创建了
screen
之后继续使用button
和select_box
(请参见在声明screen
之后被注释掉的println!()
),但是我无法这样做,因为button
和select_box
被移动到了screen
中。对我而言,解决方案似乎是让screen
借用select_box
和screen
,而不是拥有它们。然而,我不知道该如何做。我已经尝试从引用中创建盒子,例如:let screen = Screen {
components: vec![Box::new(&select_box), Box::new(&button)],
};
但是这会产生错误,例如:
the trait `Draw` is not implemented for `&SelectBox`
fn main() {
let select_box = SelectBox {
width: 75,
height: 10,
options: vec![
String::from("Yes"),
String::from("Maybe"),
String::from("No"),
],
};
let button = Button {
width: 50,
height: 10,
label: String::from("OK"),
};
let screen = Screen {
components: vec![Box::new(select_box), Box::new(button)],
};
// println!("button width: {}", button.width);
screen.run();
}
trait Draw {
fn draw(&self);
}
struct Screen {
components: Vec<Box<dyn Draw>>,
}
impl Screen {
fn run(&self) {
for component in self.components.iter() {
component.draw();
}
}
}
struct Button {
width: u32,
height: u32,
label: String,
}
impl Draw for Button {
fn draw(&self) {
println!("Button({}, {}, {})", self.width, self.height, self.label)
}
}
struct SelectBox {
width: u32,
height: u32,
options: Vec<String>,
}
impl Draw for SelectBox {
fn draw(&self) {
println!(
"SelectBox({}, {}, {})",
self.width,
self.height,
self.options.join(";")
)
}
}