How to return a Vec of Traits

Hello,

I am trying to figure out how I can allocate and return a Vector with trait references. I have seen the guidance about Sized but do not understand how to apply to this situation.

Thanks for any help!

see Playground

trait T1 {}

struct S1 {}
impl T1 for S1 {}

struct S2 {}
impl T1 for S2 {}

// ok
fn f1() -> Box<S1> {
    Box::new(S1{})
}

// ok
fn f2() -> Box<Vec<S1>> {
    Box::new(vec![S1{}])
}

// doesn't have a size known at compile-time
fn f3() -> Box<Vec<T1>> {
    Box::new(vec![S1{}])
}

// doesn't have a size known at compile-time
fn f4() -> Box<Vec<dyn T1>> {
    Box::new(vec![Box::new(S1{})])
}

fn main() {
    let _bS1 = f1();
    let _vS1 = f2();
    let _bvT1 = f3();
    let _bvbT1 = f4();
}

You probably want a Vec<Box<dyn T1>>. You don't need to box the vector – it has a very concrete type (and size). The crucial is to box the trait objects, as those are the unsized types that can't "live on their own".

So obvious - once someone explains! :slight_smile:

Thank you!