Open nikonthethird opened 5 years ago
In the first case, modify_unit
is actually a move
closure since it has to capture impl_trait
by value (it isn't Copy
). You can test this by trying to call it again. Since calling a closure via FnOnce
consumes the closure instead of mutating it, this is accepted.
In the second case, no by-value capturing is needed (instead, only unit
is captured by mutable reference), so calling the closure would AFAIK default to using FnMut
, which takes &mut self
and thus needs the variable to be mutable.
Perhaps the "cannot borrow as mutable" diagnostics could be improved in general to note the precise reason for the mutable borrow (since there are plenty of implicit ways to borrow something)
Thank you for pointing that out, it didn't occur to me at all!
This code behaves in a way that is not obvious to me:
This code compiles without any warnings in stable Rust. But notice, the
modify_unit
closure is not declaredmut
, but it modifies theunit
variable inside at location(2)
.However, when you comment out the line marked
(1)
, suddenly Rust complains that the closure is not mutable:Link to the code on the playground.
What is the reason for this behavior?