loopsrustvectoriteratorbtreemap

How to iterate over multiple collections simultaneously?


I want to loop over each element of a Vec and a BTreeMap. I'm currently doing this:

fn main() {
    let mut a = std::collections::BTreeMap::new();

    a.insert("a", "b");
    a.insert("b", "c");

    let b = vec!["hi", "Hello"];
    
    for (k, v) in a {
        for c in b.iter() {
            println!("{}, {}, {}", k, v, c);
        }
    }
}

but the output shows values printed out twice:

a, b, hi
a, b, Hello
b, c, hi
b, c, Hello

I want it to instead look like this:

a, b, hi
b, c, Hello

I know that the above is wrong (since the inner .iter() is called twice) but I don't know a different approach.


Solution

  • The keyword is "zip iterators", and it's available as Iterator::zip() and std::iter::zip():

    for ((k, v), c) in std::iter::zip(a, b) {
        println!("{}, {}, {}", k, v, c);
    }
    

    This will stop at the shorter list. itertools has also zip_longest().