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:
error[E0597]: `x` does not live long enough
--> src/main.rs:2:57
|
2 | let a: Vec<_> = (1..10).flat_map(|x| (1..x).map(|_| x)).collect();
| --- ^- - borrowed value needs to live until here
| | ||
| | |borrowed value only lives until here
| | borrowed value does not live long enough
| capture occurs here
But why?
Is is a primitive type, i.e. it should be cloned anyway.
What do I understand wrong?
This does not work because you capture
x
by reference when you domap(|_| x)
.x
is not a variable local to the closure, so it is borrowed. To not borrowx
, you must use themove
keyword:But this is more idiomatic to write (for the same output):
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.