`FnMut` is a Rust trait for a callable value that can be invoked through mutable access. A closure that changes a variable it captured from its surroundings uses `FnMut`. It can be called more than once; the name does not mean “once.” section 11.6.3 section 12.1.1
fn main() {
let mut my_string = String::from("I will be changed in the closure");
let mut my_closure = || {
my_string.push_str(" now");
println!("{my_string}");
};
my_closure();
my_closure();
}
The closure adds text to the captured string on each call. Both the string and the closure are declared `mut`, and the second call sees the first call’s change. section 11.6.3
Accepting an FnMut argument
A function can request a callable that it will invoke mutably: ```rust fn call_twice<F: FnMut()>(mut f: F) { f(); f(); } ``` The `FnMut()` bound says the callable takes no arguments and returns nothing. `mut f` lets the function call it mutably. A closure passed to `call_twice` can therefore update a captured value on each call. section 12.1.1
Choose a closure bound in a function signature according to what the callable must be allowed to do. `Fn` can be called without changing its captured environment; `FnMut` allows mutable access; `FnOnce` also allows a closure that consumes a captured value and cannot be called again. An `Fn` closure can satisfy an `FnMut` bound, and an `FnMut` closure can satisfy an `FnOnce` bound. section 11.6.3 section 12.1.2
`FnMut` also appears in iterator method signatures. In `F: FnMut(Self::Item) -> bool`, the callable receives an iterator item and returns a Boolean, as in `.all()`. The bound permits mutable invocation; it does not require the closure to change a captured variable. Functions can return a closure with a signature such as `impl FnMut(i32) -> i32`. section 12.1 section 12.2.2
