【发布时间】:2023-02-26 17:19:50
【问题描述】:
我的真实案例类似于 Rust 文档中关于 dyn trait with Screen and Draw trait 的内容。
所以我构建了一个与本书完全相似的示例。但是我不需要就地初始化向量,而是需要一个寄存器函数来将组件推送到向量中。但是我得到错误:特性 Sized 没有为 dyn Draw 实现
我不明白如何解决它...
pub trait Draw {
fn draw(&self);
}
pub struct Screen {
pub components: Vec<Box<dyn Draw>>,
}
impl Screen {
fn new() -> Self {
Screen {
components: Vec::new(),
}
}
fn register(&mut self, w: &dyn Draw) {
self.components.push(Box::new(*w));
}
fn show(&self) {
for d in self.components {
d.draw()
}
}
}
struct TextBox {
txt: String,
}
impl TextBox {
fn new(t: &str) -> Self {
TextBox { txt: t.to_string() }
}
}
struct Button {
label: String,
}
impl Button {
fn new(l: &str) -> Self {
Button {
label: l.to_string(),
}
}
}
impl Draw for TextBox {
fn draw(&self) {
println!("{}", self.txt.as_str())
}
}
impl Draw for Button {
fn draw(&self) {
println!("{}", self.label.as_str())
}
}
fn main() {
let s = Screen::new();
let b = Button::new("Button1");
let t = TextBox::new("Some text");
s.register(&b as &dyn Draw);
s.register(&t as &dyn Draw);
s.show();
}
【问题讨论】:
标签: rust traits trait-objects sized-box