I'm a few days into learning rust and have come across a problem of this sort:
struct NoCopy<T>(T);
fn main() {
let c = NoCopy(42);
let i = vec![1, 2, 4].into_iter();
let res = i.flat_map(|a| {
(0..5).map(|b| a + b + c.0)
});
for x in res {
println!("{}", x);
}
}
This won't compile because the inner closure borrows a
from the outer closure, but will outlive it. I therefore need to instruct the compiler that the inner closure should instead capture a
by value. However, the move
keyword will try to capture everything by value, including c
. Since the type of c
does not implement Copy
, this fails since the outer closure is FnMut
.
I also tried adding let a = a;
into the inner closure, which normally forces a move (I think?), but I get the same \
a` does not live long enough` error here. (Meta: Any way to escape these backticks?)
Is there any way to do this? I take it there are no C++11-style capture lists in Rust -- why not? Is there a fundamental safety issue, or is it just not yet implemented?