I have the following snippet of code:
fn f<T: FnOnce() -> u32>(c: T) {
println!("Hello {}", c());
}
fn main() {
let mut x = 32;
let g = move || {
x = 33;
x
};
g(); // Error: cannot borrow as mutable. Doubt 1
f(g); // Instead, this would work. Doubt 2
println!("{}", x); // 32
}
Doubt 1
I can not run my closure even once.
Doubt 2
... but I can invoke that closure as many times as I want, provided that I call it through f. Funnily, if I declare it FnMut, I get the same error as in doubt 1.
Doubt 3
What does self refer to in Fn, FnMut and FnOnce traits definition? Is that the closure itself? Or the environment?
E.g. from the documentation:
pub trait FnMut<Args>: FnOnce<Args> {
extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output;
}