Rust Vector of Traits: Throw Every Character

I have a problem translating a feature vector into a vector with different features.

Using an array / vector approach for replicating in Rust , I basically tried the following:

trait ParentTrait {}

trait ChildTrait: ParentTrait {}

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

Now it does not compile, it leads to

error: the trait `core::kinds::Sized` is not implemented for the type `ChildTrait`
[...]
error: the trait `ParentTrait` is not implemented for the type `ChildTrait`
[...]

(The second error is the erroneous behavior of the compiler, I think?)

I tried various other link / box options and couldn't get it to work.

What am I doing wrong here, is it even the right approach with newer versions of rust (0.13)?

+1
source share
1 answer

Object objects are very strange animals.

Box<ChildTrait>? Box<T> *mut T. a Box<ChildTrait> *mut ChildTrait. ChildTrait , ChildTrait . : vtable .

, , vtable vtable . ,

the trait `ParentTrait` is not implemented for the type `ChildTrait`

, , . , ParentTrait :

trait ParentTrait for Sized? {}

impl ParentTrait ChildTrait:

impl<'a> ParentTrait for ChildTrait+'a {}

, :

<anon>:9:40: 9:42 error: cannot move out of dereference of `&`-pointer
<anon>:9     let parents = children.iter().map(|&e| e as Box<ParentTrait>);
                                                ^~
<anon>:9:41: 9:42 note: attempting to move value to here
<anon>:9     let parents = children.iter().map(|&e| e as Box<ParentTrait>);
                                                 ^
<anon>:9:41: 9:42 help: to prevent the move, use `ref e` or `ref mut e` to capture value by reference
<anon>:9     let parents = children.iter().map(|&e| e as Box<ParentTrait>);

into_iter iter Vec:

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);
}

, ICE .

+1

Source: https://habr.com/ru/post/1678555/


All Articles