Hi all, I'm learning deeper closures in Rust, after you have and write here the normal examples, please read it carefully, this question is closer to how Rust works, than a way to use closure. Maybe still the answer is simple and obvious, but lets keep digging.
The normal definition: Rust’s closures are anonymous functions you can save in a variable or pass as arguments to other functions.
Just that definition is far from enough to describe it.
let mut counter = 0;
let mut f_counter = move || {
counter += 1;
println!("{}", counter);
};
f_counter();
f_counter();
We will get 1 and 2 as result.... so is not only picking and moving a env var to the closure, the variable inside also persist after each call... Which open a very big door in how to store and handle data... think this also put me to think... is this all? are there more hidden things?
Next point, return type...
In the example above, f_counter
is a... something? I'll write its properties...
Is shows as the Trait FnMut
Can be called, a normal Trait can not be called
It can be used as a generic while a trait can not be used like that
Even if it shows as a trait, we can't use it for trait bounds, we can parse it as a type, but when want to write the trait bounds, we need to write manually exactly the same declared trait bound of the closure (yes, this can be known in compile time).
So, after all this, my conclusion is that a Closure is not a trait, in the example, f_counter
is something that has implemented the FnMut
trait.
To me, rn, this thing is closer to a thread with a loop waiting to run and ready to be used.
For now, I'm not very sure what a Closure is, I can use them, but would be nice to know this questions. Maybe Rust-Analyzer only shows it as a Trait because is useful know that info, even if is not the right answer.
Thx!