Search code examples
rustiteratortraits

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.


Solution

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