0

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>);
}

playground

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
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Andrew Mackenzie
  • 5,477
  • 5
  • 48
  • 70
  • [The duplicate's solution applied to your specific case](https://play.integer32.com/?gist=52a607905087578440b176cc10fe7607&version=stable). Notably, it doesn't make sense to cast the entire vector at once. – Shepmaster Dec 09 '17 at 21:46
  • See also: [Create vector of objects implementing a trait in Rust](https://stackoverflow.com/q/38134158/155423). – Shepmaster Dec 09 '17 at 21:50

0 Answers0