vectorrustiteratortraitsrust-itertools

How do I interlace two Rust vectors into a new vector?


I need an idiomatic way to interlace these two vectors:

v1 = vec![1.0, 2.0, 3.0];
v2 = vec![4.0, 5.0, 6.0];

The output I expect is:

v3 is [1.0, 4.0, 2.0, 5.0, 3.0, 6.0];

I attempted using itertool's interlace function, but I can't get the iterators to collect to Vec types. It's likely I'm using them wrong.


Solution

  • Using interleave() function or interleave() method from Itertools crate:

    use itertools::{interleave, Itertools};
    
    fn main() {
        let v1 = vec![1.0, 2.0, 3.0];
        let v2 = vec![4.0, 5.0, 6.0];
        let v = interleave(v1, v2).collect::<Vec<_>>();
        dbg!(v);
    
        let v1 = vec![1.0, 2.0, 3.0];
        let v2 = vec![4.0, 5.0, 6.0];
        let v = v1
            .into_iter()
            .interleave(v2.into_iter())
            .collect::<Vec<_>>();
        dbg!(v);
    }