2015-01-10 46 views
1

我想創建一個新的矢量,其中包含實現Trait的對象,這些矢量是我已經擁有的包含這些對象的矢量。如何從實現Trait的類型的向量創建Trait的新向量?

trait Foo { 
    // 
} 


struct Bar { 
    i: i32, 
} 


struct Baz { 
    c: char, 
} 

impl Foo for Bar { 
    // 
} 

impl Foo for Baz { 
    // 
} 
fn main() { 
    let v1 = vec![Bar{i: 2},Bar{i: 4}]; 
    let v2 = vec![Baz{c: '2'},Baz{c: '4'}]; 

    let mut v_all: Vec<Box<Foo>> = Vec::new(); 

    v_all.extend(v1.into_iter()); 
    v_all.extend(v2.into_iter()); 

} 

這當然讓我

<anon>:34:11: 34:33 error: type mismatch resolving `<collections::vec::IntoIter<Bar> as core::iter::Iterator>::Item == Box<Foo>`: expected struct Bar, found box 
<anon>:34  v_all.extend(v1.into_iter()); 

如果可能的話我怎麼能做到這一點,?

回答

3

好吧,如果你有一個Bar,你需要一個Box<Foo>,那麼您需要首先框中的值,然後將其轉換爲特徵的對象,它看起來像這樣:

v_all.extend(v1.into_iter().map(|e| Box::new(e) as Box<Foo>)); 
v_all.extend(v2.into_iter().map(|e| Box::new(e) as Box<Foo>));