Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to explicitly write the type of a closure?

Tags:

closures

rust

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 with different signatures have different types, but different closures with the same signature have different types, as well.

Is there a way to explicitly write the type signature of a closure? Is there any compiler flag that expands the type of inferred closure?

like image 632
basic_bgnr Avatar asked Mar 22 '15 04:03

basic_bgnr


1 Answers

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());
}
like image 89
Shepmaster Avatar answered Nov 15 '22 09:11

Shepmaster