How can I zip more than two iterators?

2019-03-17 13:41发布

问题:

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 iter = a.iter()
        .zip(b.iter())
        .zip(c.iter())
        .map(|((x, y), z)| (x, y, z));
}

That is, how can I build an iterator from n iterables which yields n-tuples?

回答1:

You can use the izip!() macro from the crate itertools, which implements this for arbitrary many iterators:

#[macro_use]
extern crate itertools;

fn main() {

    let a = [1, 2, 3];
    let b = [4, 5, 6];
    let c = [7, 8, 9];

    // izip!() accepts iterators and/or values with IntoIterator.
    for (x, y, z) in izip!(&a, &b, &c) {

    }
}

You would have to add a dependency on itertools in Cargo.toml, use whatever version is the latest. Example:

[dependencies]
itertools = "0.7"


标签: iterator rust