fn main() {
let mut a = String::from(\"a\");
let closure = || {
a.push_str(\"b\");
};
closure();
}
This won\'t compile:
There are 3 function traits in Rust: Fn
, FnMut
and FnOnce
. Going backward:
FnOnce
only guarantees that the value can be called once,FnMut
only guarantees that the value can be called if it is mutable,Fn
guarantees that the value can be called, multiple times, and without being mutable.A closure will automatically implement those traits, depending on what it captures and how it uses it. By default, the compiler will pick the least restrictive trait; so favor Fn
over FnMut
and FnMut
over FnOnce
.
In your second case:
let mut a = String::from("a");
let closure = || {
a.push_str("b");
a
};
This closure requires being able to return a
, which requires FnOnce
. It moves a
into the capture. If you tried to call your closure a second time, it would fail to compile. If you tried to access a
, it would fail to compile too.
This is why FnOnce
is a "last resort" implementation.
On the other hand your first case:
let mut a = String::from("a");
let closure = || {
a.push_str("b");
};
At most requires a mutable reference to a
, and therefore the capture occurs by mutable reference. Since it captures a mutable reference, the closure implements FnMut
, and therefore can only be called if it is itself mutable.
If you remove mut
, in front of a
, the compiler will signal to you it needs to borrow a
mutably.
The compiler does not require that closure
itself be declared mutably until you attempt to call it; after all you could pass it by value to a function without calling it (yourself), in which case mut
would be superfluous.