Return Vector of Boxed objects

Viewed 54

I am trying to return a vector of dynamic objects, so I'm wrapping each element in a Box. This works when I initialise a vector and immediately return it, but it does not work if I create a temporary variable.

I really need the second method, because I would like to do some operations before actually returning the vector.

Here's a minimal reproducable example:

trait Dynamic {
    fn foo(&self);
} 

struct Concrete {
    bar: i32
}

impl Concrete {
    fn new(value: i32) -> Self {
        Self {
            bar: value
        }
    }
}

impl Dynamic for Concrete {
    fn foo(&self) {
        todo!()
    }
}

fn generate() -> Vec<Box<dyn Dynamic>> {
    // this works
    vec![
        Box::new(Concrete::new(1)),
        Box::new(Concrete::new(3))
    ]

    // ------------------------------------------------------------------------------------------------
    // this does not work with the error: expected `Vec<Box<(dyn Dynamic + 'static)>>`
    let temp = vec![
        Box::new(Concrete::new(1)),
        Box::new(Concrete::new(3))
    ];

    temp
}

fn main() {
    let result = generate();
    
    println!("Hello, world!");
}

I'm not sure where the 'static is coming from. I don't want the elements in the vector to be static either, because in the future, I need to read these values from a file or other external provider so they won't be static.

1 Answers

Just annotate your temp variable with the proper type:

let temp: Vec<Box<dyn Dynamic>> = vec![
    Box::new(Concrete::new(1)),
    Box::new(Concrete::new(3))
];

Playground

Related