Iterator of items to iterator of pairs

So I've got a Vec<String> that's a flattened list of keys and values. I want to iterate over the key/value pairs. I've got this, which works:

let kvlist: Vec<String> = ....;

for i in (0..kvlist.len()).step_by(2) {
    println!("key={} value={}", kvlist[i], kvlist[i] + 1);
}

But it seems like it ought to be easy to do this:

for (key, value) in kvlist.some_iterator_magic() {
    println!("key={} value={}", key, value);
}

But I don't know what to replace some_iterator_magic with. I figure I could use skip() and step_by() to create iterators on the keys and the values, and then zip() to create an iterator of pairs over the two, but that doesn't seem like an improvement. Is there something obvious I'm missing? Maybe I can create two slices and zip them?

3 Likes

chunks(2)?

2 Likes

That's certainly better:

let kvlist: &[String] = ...;

for pair in kvlist.chunks(2) {
    println!("key={} value={}", pair[0], pair[1]);
}

And then if really wanted a tuple, I could use map, I suppose.

1 Like

You might want to take a look at how it's done in Itertools, too.

1 Like

I shall, though for my current project I'm trying to limit use of external dependencies. Or is itertools one of those crates like lazy_static that might as well be part of std::?

It may as well be part of std, it provides a large number of interesting and useful iterator combinators.

And it works with no_std, which may be an issue for this project eventually.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.