我想从两个实现特征的对象向量中创建特征对象的向量,这样我就可以在数组中的每个对象上调用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>);
}
这有错误:
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