There is an error in this piece of code:
let a: Vec<_> = (1..10).flat_map(|x| (1..x).map(|_| x)).collect();
The error message:
<This does not work because you capture x
by reference when you do map(|_| x)
. x
is not a variable local to the closure, so it is borrowed. To not borrow x
, you must use the move
keyword:
let a: Vec<_> = (1..10).flat_map(|x| (1..x).map(move |_| x)).collect();
But this is more idiomatic to write (for the same output):
use std::iter::repeat;
let b: Vec<_> = (2..10).flat_map(|x| repeat(x).take(x - 1)).collect();
Concerning the "why" question: some people could want to borrow a copyable data, so the capturing rules are the same:
move
keyword: take the ownership.