简体   繁体   中英

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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