I started reading the Rust guide on closures. From the guide:
That is because in Rust each closure has its own unique type. So, not only do closures w
No. The real type of a closure is only known to the compiler, and it's not actually that useful to be able to know the concrete type of a given closure. You can specify certain "shapes" that a closure must fit, however:
fn call_it<F>(f: F)
where
F: Fn(u8) -> u8, // <--- HERE
{
println!("The result is {}", f(42))
}
fn main() {
call_it(|a| a + 1);
}
In this case, we say that call_it
accepts any type that implements the trait Fn
with one argument of type u8
and a return type of u8
. Many closures and free functions can implement that trait however.
As of Rust 1.26.0, you can also use the impl Trait
syntax to accept or return a closure (or any other trait):
fn make_it() -> impl Fn(u8) -> u8 {
|a| a + 1
}
fn call_it(f: impl Fn(u8) -> u8) {
println!("The result is {}", f(42))
}
fn main() {
call_it(make_it());
}