What is going wrong here?
fn main() {
// scope 1
let mut i = 0u32;
let _ = (0..2)
.map(|_| {
// scope 2
// error : captured variable cannot escape `FnMut` closure body
(0..2).map(|_| {
// scope 3
i += 1;
})
});
}
The full error is:
error: captured variable cannot escape `FnMut` closure body
--> src/main.rs:8:13
|
3 | let mut i = 0u32;
| ----- variable defined here
4 | let _ = (0..2)
5 | .map(|_| {
| - inferred to be a `FnMut` closure
...
8 | / (0..2).map(|_| {
9 | | // scope 3
10 | | i += 1;
| | - variable captured here
11 | | })
| |______________^ returns a reference to a captured variable which escapes the closure body
|
= note: `FnMut` closures only have access to their captured variables while they are executing...
= note: ...therefore, they cannot allow references to captured variables to escape
What is going on?
- Why does adding
moveto parameter list of the second closure make the problem go away? - The full error message says that the second closure "returns a reference to a captured variable which escapes the closure body"? But the function returns unit. So what is rustc thinking? And what are the references? Is the
iin scope 3 really a reference to an invisible reference in scope 2 to theiin scope 1? - Why does changing the second
maptofor_eachmake the problem go away?