基于引用的Trait对象

3
以下是大致来自 Rust 书籍第17.2章的特质对象示例。对于我的用例,我想在创建了screen之后继续使用buttonselect_box(请参见在声明screen之后被注释掉的println!()),但是我无法这样做,因为buttonselect_box被移动到了screen中。对我而言,解决方案似乎是让screen借用select_boxscreen,而不是拥有它们。然而,我不知道该如何做。我已经尝试从引用中创建盒子,例如:
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(";")
        )
    }
}
3个回答

2
通常的解决方案是为&T&mut T编写一个适用于所有实现了T: Draw特质的统一实现:
impl<T: ?Sized + Draw> Draw for &'_ T {
    fn draw(&self) {
        <T as Draw>::draw(&**self)
    }
}
impl<T: ?Sized + Draw> Draw for &'_ mut T {
    fn draw(&self) {
        <T as Draw>::draw(&**self)
    }
}

然而,你又遇到了另一个错误:
error[E0597]: `select_box` does not live long enough
  --> src/main.rs:17:35
   |
17 |         components: vec![Box::new(&select_box), Box::new(&button)],
   |                          ---------^^^^^^^^^^^-
   |                          |        |
   |                          |        borrowed value does not live long enough
   |                          cast requires that `select_box` is borrowed for `'static`
...
21 | }
   | - `select_box` dropped here while still borrowed

error[E0597]: `button` does not live long enough
  --> src/main.rs:17:58
   |
17 |         components: vec![Box::new(&select_box), Box::new(&button)],
   |                                                 ---------^^^^^^^-
   |                                                 |        |
   |                                                 |        borrowed value does not live long enough
   |                                                 cast requires that `button` is borrowed for `'static`
...
21 | }
   | - `button` dropped here while still borrowed

这是因为dyn Trait实际上是dyn Trait + 'static。您需要添加一个生命周期参数:

struct Screen<'a> {
    components: Vec<Box<dyn Draw + 'a>>,
}

impl Screen<'_> {

Playground.


1

您可以使用Rc代替Box,使得screen和主函数能够同时引用select_boxbutton这两个组件。

use std::rc::Rc;
fn main() {
    let select_box = Rc::new(SelectBox {
        width: 75,
        height: 10,
        options: vec![
            String::from("Yes"),
            String::from("Maybe"),
            String::from("No"),
        ],
    });
    let button = Rc::new(Button {
        width: 50,
        height: 10,
        label: String::from("OK"),
    });
    let screen = Screen {
        components: vec![select_box.clone(), button.clone()],
    };
    println!("button width: {}", button.width);
    screen.run();
}

trait Draw {
    fn draw(&self);
}

struct Screen {
    components: Vec<Rc<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(";")
        )
    }
}

Playground

以下是输出结果:

button width: 50
SelectBox(75, 10, Yes;Maybe;No)
Button(50, 10, OK)

1

特质对象可以通过任何指针类型(如引用、RcArc等)使用,而不仅限于Box。因此,如果您想让Screen借用组件,您可以简单地存储代表组件的Draw特质对象的引用

struct Screen<'c> {
    components: Vec<&'c dyn Draw>,
}

impl Screen<'_> {
    fn run(&self) {
        for component in self.components.iter() {
            component.draw();
        }
    }
}

Playground


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接