How can I zip more than two iterators?

前端 未结 3 936
南笙
南笙 2020-12-29 20:32

Is there a more direct and readable way to accomplish the following:

fn main() {
    let a = [1, 2, 3];
    let b = [4, 5, 6];
    let c = [7, 8, 9];
    let         


        
3条回答
  •  有刺的猬
    2020-12-29 21:23

    You could also create a macro using the .zip provided like,

    $ cat z.rs
    macro_rules! zip {
        ($x: expr) => ($x);
        ($x: expr, $($y: expr), +) => (
            $x.iter().zip(
                zip!($($y), +))
        )
    }
    
    
    fn main() {
        let x = vec![1,2,3];
        let y = vec![4,5,6];
        let z = vec![7,8,9];
    
        let zipped = zip!(x, y, z);
        println!("{:?}", zipped);
        for (a, (b, c)) in zipped {
            println!("{} {} {}", a, b, c);
        }
    }
    

    Output:

    $ rustc z.rs && ./z
    Zip { a: Iter([1, 2, 3]), b: Zip { a: Iter([4, 5, 6, 67]), b: IntoIter([7, 8, 9]), index: 0, len: 0 }, index: 0, len: 0 }
    1 4 7
    2 5 8
    3 6 9
    

提交回复
热议问题