Vector 性状的锈菌载体:铸造每个性状

Vector 性状的锈菌载体:铸造每个性状,vector,casting,rust,traits,Vector,Casting,Rust,Traits,我有一个问题,把一个特征向量转换成一个不同特征向量 使用的方法,我基本上尝试了以下几点: trait ParentTrait {} trait ChildTrait: ParentTrait {} fn main() { let mut children: Vec<Box<ChildTrait>> = vec![]; let parents = children.iter().map(|&e| e as Box<ParentTrait&g

我有一个问题,把一个特征向量转换成一个不同特征向量

使用的方法,我基本上尝试了以下几点:

trait ParentTrait {}

trait ChildTrait: ParentTrait {}

fn main() {
    let mut children: Vec<Box<ChildTrait>> = vec![];
    let parents = children.iter().map(|&e| e as Box<ParentTrait>);
}
(我想第二个错误是编译器的错误行为?)

我尝试了各种其他风格的参考资料/方框,但都没能成功

我做错了什么,
对于更新版本的rust(0.13),这是正确的方法吗?

特质对象是非常奇怪的野兽

什么是
Box
实际上是
*mut
的包装器。因此,一个
包装了一个
*mut ChildTrait
。因为
ChildTrait
命名了一个特征,
ChildTrait
是一个。指向对象类型的指针由一对指针表示:指向该trait的vtable的指针,仅指向该trait,以及指向实际值的指针

当我们从另一个特性继承一个特性时,这并不意味着我们可以从第二个特性的vtable指针获得第一个特性的vtable指针。这就是编译器抱怨的原因

the trait `ParentTrait` is not implemented for the type `ChildTrait`
但是,我们可以手动实现对象类型的特征。由于对象类型没有大小,我们必须首先允许为未大小的类型实现
ParentTrait

trait ParentTrait for Sized? {}
然后我们可以为
ChildTrait
对象类型提供
ParentTrait
impl

impl<'a> ParentTrait for ChildTrait+'a {}
但是我们得到了一个内部编译器错误:

error: internal compiler error: trying to take the sizing type of ChildTrait, an unsized type
note: the compiler unexpectedly panicked. this is a bug.
note: we would appreciate a bug report: http://doc.rust-lang.org/complement-bugreport.html
note: run with `RUST_BACKTRACE=1` for a backtrace
task 'rustc' panicked at 'Box<Any>', /build/rust-git/src/rust/src/libsyntax/diagnostic.rs:175
错误:内部编译器错误:尝试采用ChildTrait的大小调整类型,一种未大小调整的类型
注意:编译器出人意料地惊慌失措。这是一个错误。
注意:如果您能提供错误报告,我们将不胜感激:http://doc.rust-lang.org/complement-bugreport.html
注意:使用'RUST_BACKTRACE=1'运行回溯跟踪
任务'rustc'在'Box'处惊慌失措,/build/rust-git/src/rust/src/libsyntax/diagnostic.rs:175
此代码也会出现相同的错误:

fn main() {
    let mut children: Vec<Box<ChildTrait>> = vec![];
    let parents = children.iter().map(|e| &**e as &ParentTrait);
}
fn main(){
让mut子对象:Vec=Vec![];
让parents=children.iter().map(|e |和**e as&ParentTrait);
}

在这一点上,我不知道在修复ICE后,这是否会成功编译。

谢谢您的解释!你知道这是否是一个已知的bug吗?否则我会提交一份新的bugreport。确认目前不可能以这种方式铸造特征,但将来应该会出现。
fn main() {
    let mut children: Vec<Box<ChildTrait>> = vec![];
    let parents = children.into_iter().map(|e| e as Box<ParentTrait>);
}
error: internal compiler error: trying to take the sizing type of ChildTrait, an unsized type
note: the compiler unexpectedly panicked. this is a bug.
note: we would appreciate a bug report: http://doc.rust-lang.org/complement-bugreport.html
note: run with `RUST_BACKTRACE=1` for a backtrace
task 'rustc' panicked at 'Box<Any>', /build/rust-git/src/rust/src/libsyntax/diagnostic.rs:175
fn main() {
    let mut children: Vec<Box<ChildTrait>> = vec![];
    let parents = children.iter().map(|e| &**e as &ParentTrait);
}