如何从实现特征的对象向量创建特征对象的向量?

时间:2017-12-09 21:37:36

标签: rust

我想从两个实现特征的对象向量中创建特征对象的向量,这样我就可以在数组中的每个对象上调用trait方法,与实际对象类型不同:

struct Value;
struct Function;
pub trait Runnable {
    fn get(&self);
}

impl Runnable for Function {
    fn get(&self) {}
}
impl Runnable for Value {
    fn get(&self) {} 
}

fn main() {
    let value = Value{};
    let values = Vec::<&Value>::new();
    values.push(&value);

    let function = Function{};
    let functions = Vec::<&Function>::new();
    functions.push(&function);

    let mut runnables = Vec::<&Runnable>::new();
    runnables.append(&mut values as &mut Vec<&Runnable>);
    runnables.append(&mut functions as &mut Vec<&Runnable>);
}

playground

这有错误:

error[E0605]: non-primitive cast: `&mut std::vec::Vec<&Value>` as `&mut std::vec::Vec<&Runnable>`
  --> src/main.rs:24:22
   |
24 |     runnables.append(&mut values as &mut Vec<&Runnable>);
   |                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: an `as` expression can only be used to convert between primitive types. Consider using the `From` trait

error[E0605]: non-primitive cast: `&mut std::vec::Vec<&Function>` as `&mut std::vec::Vec<&Runnable>`
  --> src/main.rs:25:22
   |
25 |     runnables.append(&mut functions as &mut Vec<&Runnable>);
   |                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: an `as` expression can only be used to convert between primitive types. Consider using the `From` trait

0 个答案:

没有答案