I'd like to create a vector of trait objects from two vectors of objects that implement the trait so I can call the trait methods on each object in the array indistinctly of the actual object type:
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>);
}
This has the error:
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