首页 > 解决方案 > 如何从实现该特征的结构迭代器中收集特征向量

问题描述

我正在尝试从实现该特征的结构迭代器中获取特征向量。

到目前为止,我能够做到这一点:

    fn foo() -> Vec<Box<dyn SomeTrait>> {
        let v: Vec<_> = vec![1]
            .iter()
            .map(|i| {
                let b: Box<dyn SomeTrait> = Box::new(TraitImpl { id: *i });
                b
            })
            .collect();
        v
    }

但我想让它更简洁。

标签: rustiteratortraits

解决方案


这对我有用。操场

虽然我不是 Rust 大师,所以我不确定'staticfoo<S: SomeTrait + 'static>

trait SomeTrait { fn echo(&self); }
impl SomeTrait for u32 {
    fn echo(&self) {
        println!("{}", self);
    }
}

fn foo<S: SomeTrait + 'static>(iter: impl Iterator<Item=S>) -> Vec<Box<dyn SomeTrait>> {
    iter.map(|e| Box::new(e) as Box<dyn SomeTrait>).collect()
}

fn main() {
    let v = vec!(1_u32, 2, 3);
    let sv = foo(v.into_iter());
    sv.iter().for_each(|e| e.echo());
}

推荐阅读