Why can't Vecs hold &dyn Trait, but arrays can?

// store trait objects (where trait = KnowsItsLeader) into an array. This works:

let a: [&dyn KnowsItsLeader;2] = [&d, &m];

    for trait_object in a.iter() {

        println!("Invoked via array: {}", trait_object.get_my_leader());

    }

    // let's try same thing in Vector. This does not work, complains that the type of items
    // being stored in a struct of d's type and that m doesn't have the same type. Why
    // doesn't my explicit type make it clear that I'm storing trait object and not structs

    let v: &dyn KnowsItsLeader = vec![&d, &m];

My question is why can I store trait objects in an array (see first part of code above) but the same approach doesn't work with vector? (see second part of code above)

Michael

let v: &dyn KnowsItsLeader = vec![…

This is incorrect, because the type is Vec<&dyn KnowsItsLeader>. You forgot it's wrapped in a Vec, not a single element.

3 Likes