【问题标题】:How do I create a new vector of Trait from vectors of types that implement Trait?如何从实现 Trait 的类型的向量中创建一个新的 Trait 向量?
【发布时间】:2015-01-11 02:37:07
【问题描述】:

我想创建一个新向量,其中包含实现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());

如果可能的话,我怎样才能做到这一点?

【问题讨论】:

    标签: vector rust traits


    【解决方案1】:

    好吧,如果你有一个Bar,并且你需要一个Box&lt;Foo&gt;,那么你需要先将值装箱,然后将其转换为一个特征对象,如下所示:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 2016-02-15
      • 1970-01-01
      • 2015-05-31
      • 2017-03-10
      • 1970-01-01
      相关资源
      最近更新 更多