Lifetime of values inside flat_map followed by collect

Hi,

I got an error "n does not live long enough" with the following code.
However, I don't see how to clone this n with the expected lifetime.
The chain of .iter().map(|n|n.clone()).flat_map doesn't work and .into_iter() doesn't either.
Could you let me know how do you handle this pattern?

pub fn sum_of_multiples(limit: u32, factors: &[u32]) -> u32 {
  let mut numbers = factors.iter().flat_map(
    |&n|(0..limit).filter(|&i|i%n==0)
  ).collect::<Vec<_>>();
  numbers.sort();
  numbers.dedup();
  numbers.iter().fold(0,|a,b|a+b)
}

error

You just need to move the n value into that 2nd/inner closure so that it captures the value, and not a reference to the "outer" n:

// note the `move` in the 2nd closure
.flat_map(|&n| (0..limit).filter(move |&i| i % n == 0))
1 Like

Aha! Thanks, vitalyd!