简体   繁体   English

如何从实现该特征的结构迭代器中收集特征向量

[英]How can I collect a vector of Traits from an iterator of structs implementing that trait

I'm trying to get a vector of traits from an iterator of structs implementing that trait.我正在尝试从实现该特征的结构迭代器中获取特征向量。

So far I was able to do this:到目前为止,我能够做到这一点:

    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
    }

But I would like to make it more concise.但我想让它更简洁。

This works for me.这对我有用。 Playground 操场

Though I'm not a Rust guru, so I'm not sure about 'static limitation in foo<S: SomeTrait + 'static>虽然我不是 Rust 大师,但我不确定'static foo<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());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM