For-loop over `Map` without consuming it

Is there a way to for-loop over my_iter.map() without using .collect()?

Example1 - this doesn't work

fn main() {
    let v = vec![1,2,3];
    let map = v.iter().map(|x| 2*x);
    for &v in &map {
        println!("{v}");
    }
    // println!("{:?}", map);
}

nor does replacing the for <...> line with

  • for v in &map
  • for v in map.iter()
  • for v in map.iter_mut()

But what does work is

fn main() {
    let v = vec![1,2,3];
    let map = v.iter().map(|x| 2*x);
    let vec: Vec<_> = map.collect();
    for v in &vec {
        println!("{v}");
    }
    println!("{:?}", vec);
}

Is there a way to keep using map without having to call `.collect() before the for-loop?

This works, but might not for more complicated situations:

fn main() {
    let v = vec![1,2,3];
    let map = v.iter().map(|x| 2*x);
    for v in map.clone() {
        println!("{v}");
    }
    println!("{:?}", map);
}

Fundamentally, map is lazy— It only runs the function that you give it when a new item is requested, and that result isn’t stored anywhere. If you want to use the results multiple times, you either need to store them yourself (e.g. via collect) or recalculate them the second time (what this snippet does).

4 Likes

Thank you, I only found .by_ref(), which was useless in my case. Must have overlooked :clone() in the docs.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.