【问题标题】:Error E0277 following book example dyn Trait, how to push a dyn trait in vector?书中示例 dyn Trait 后出现错误 E0277,如何在 vector 中推送 dyn trait?
【发布时间】: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


    【解决方案1】:

    您不能取消引用 &amp;dyn Trait,因为那样会在堆栈上创建未知大小的内容。 相反,您可以取 impl Trait 并将其装箱或直接取 Box&lt;dyn Draw&gt;

        fn register(&mut self, w: impl Draw + 'static) {
            self.components.push(Box::new(w));
        }
    

    并传入对象本身而不是对它们的引用:

        let b = Button::new("Button1");
        let t = TextBox::new("Some text");
        s.register(b);
        s.register(t);
    

    注意:+ 'static 意味着 w 不能包含任何短于 'static 的引用不是意味着w必须永远活着。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-01
      • 2021-12-04
      • 2023-03-29
      相关资源
      最近更新 更多