Why does Rust not allow coercion to trait objects inside containers?

£可爱£侵袭症+ 提交于 2019-12-19 16:56:09

问题


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.



来源:https://stackoverflow.com/questions/41889727/why-does-rust-not-allow-coercion-to-trait-objects-inside-containers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!