This code is an inefficient way of producing a unique set of items from an iterator. To accomplish this, I am attempting to use a Vec
to keep track of values I've seen. I believe that this Vec
needs to be owned by the innermost closure:
fn main() {
let mut seen = vec![];
let items = vec![vec![1i32, 2], vec![3], vec![1]];
let a: Vec<_> = items
.iter()
.flat_map(move |inner_numbers| {
inner_numbers.iter().filter_map(move |&number| {
if !seen.contains(&number) {
seen.push(number);
Some(number)
} else {
None
}
})
})
.collect();
println!("{:?}", a);
}
However, compilation fails with:
error[E0507]: cannot move out of captured outer variable in an `FnMut` closure
--> src/main.rs:8:45
|
2 | let mut seen = vec![];
| -------- captured outer variable
...
8 | inner_numbers.iter().filter_map(move |&number| {
| ^^^^^^^^^^^^^^ cannot move out of captured outer variable in an `FnMut` closure
It seems that the borrow checker is getting confused at the nested closures + mutable borrow. It might be worth filing an issue.Edit: See huon's answer for why this isn't a bug.As a workaround, it's possible to resort to
RefCell
here:This is a little surprising, but isn't a bug.
flat_map
takes aFnMut
as it needs to call the closure multiple times. The code withmove
on the inner closure fails because that closure is created multiple times, once for eachinner_numbers
. If I write the closures in explicit form (i.e. a struct that stores the captures and an implementation of one of the closure traits) your code looks (a bit) likeWhich makes the illegality clearer: attempting to move out of the
&mut OuterClosure
variable.Theoretically, just capturing a mutable reference is sufficient, since the
seen
is only being modified (not moved) inside the closure. However things are too lazy for this to work...Removing the
move
s makes the closure captures work like(I've named the
&mut self
lifetime in this one, for pedagogical purposes.)This case is definitely more subtle. The
FilterMap
iterator stores the closure internally, meaning any references in the closure value (that is, any references it captures) have to be valid as long as theFilterMap
values are being thrown around, and, for&mut
references, any references have to be careful to be non-aliased.The compiler can't be sure
flat_map
won't, e.g. store all the returned iterators in aVec<FilterMap<...>>
which would result in a pile of aliased&mut
s... very bad! I think this specific use offlat_map
happens to be safe, but I'm not sure it is in general, and there's certainly functions with the same style of signature asflat_map
(e.g.map
) would definitely beunsafe
. (In fact, replacingflat_map
withmap
in the code gives theVec
situation I just described.)For the error message:
self
is effectively (ignoring the struct wrapper)&'b mut (&'a mut Vec<i32>)
where'b
is the lifetime of&mut self
reference and'a
is the lifetime of the reference in thestruct
. Moving the inner&mut
out is illegal: can't move an affine type like&mut
out of a reference (it would work with&Vec<i32>
, though), so the only choice is to reborrow. A reborrow is going through the outer reference and so cannot outlive it, that is, the&mut *self.seen
reborrow is a&'b mut Vec<i32>
, not a&'a mut Vec<i32>
.This makes the inner closure have type
InnerClosure<'b>
, and hence thecall_mut
method is trying to return aFilterMap<..., InnerClosure<'b>>
. Unfortunately, theFnMut
trait definescall_mut
as justIn particular, there's no connection between the lifetime of the
self
reference itself and the returned value, and so it is illegal to try to returnInnerClosure<'b>
which has that link. This is why the compiler is complaining that the lifetime is too short to be able to reborrow.This is extremely similar to the
Iterator::next
method, and the code here is failing for basically the same reason that one cannot have an iterator over references into memory that the iterator itself owns. (I imagine a "streaming iterator" (iterators with a link between&mut self
and the return value innext
) library would be able to provide aflat_map
that works with the code nearly written: would need "closure" traits with a similar link.)Work-arounds include:
RefCell
suggested by Renato Zannon, which allowsseen
to be borrowed as a shared&
. The desugared closure code is basically the same other than changing the&mut Vec<i32>
to&Vec<i32>
. This change means "reborrow" of the&'b mut &'a RefCell<Vec<i32>>
can just be a copy of the&'a ...
out of the&mut
. It's a literal copy, so the lifetime is retained..collect::<Vec<_>>()
ing inside the loop to run through the wholefilter_map
before returning.I imagine the
RefCell
version is more efficient.