HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustMajor

How can I zip more than two iterators?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howiteratorsthancanziptwomore

Problem

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?

Solution

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

use itertools::izip;

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.8"

Code Snippets

[dependencies]
itertools = "0.8"

Context

Stack Overflow Q#29669287, score: 95

Revisions (0)

No revisions yet.