Why does Rust not allow coercion to trait objects

2020-04-03 10:15发布

问题:

I have a Vec<Box<T>> where T implements Foo. Why can I not coerce it to a Vec<Box<Foo>> even though I can coerce anything of type Box<T> into a Box<Foo>? Why does the below code not compile?

use std::vec;

trait Foo {}

struct Bar {}

impl Foo for Bar {}

fn main() {
    let v = vec![Box::new(Bar {})];
    let v_1 = v as Vec<Box<Foo>>;
}

回答1:

Because Box<Bar> is a different size than Box<Foo>. The coercion is allowed on a single value, but here you'd have to resize the whole vector. The book goes into some detail on this in the section on Representation of Trait Objects. Short version: Box<Bar> is a pointer to a value. Box<Foo> is a pointer to a value and a pointer to a vtable.