为什么Rust不允许强制性特征容器内的对象? [英] Why does Rust not allow coercion to trait objects inside containers?
问题描述
我有一个 Vec< Box< T>>
其中 T
implements Foo
。为什么我不能强迫 Vec< Box< Foo>>
>,即使我可以强制任何类型的 Box< T>
转换为 Box< Foo>
?为什么下面的代码不能编译?
使用std :: vec;
特性Foo {}
struct Bar {}
impl Foo for Bar {}
fn main() {
让v = vec![Box :: new(Bar {})];
让v_1 = v为Vec< Box< Foo>>;
因为 Box< Bar>
与 Box< Foo>
大小不同。强制只允许在一个单个值上,但在这里您必须调整整个向量的大小。本书在特征对象表示一节中详细介绍了这一点。短版本: Box< Bar>
是指向值的指针。 Box< Foo>
是一个指向值和指针的指针。
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>>;
}
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.
这篇关于为什么Rust不允许强制性特征容器内的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!