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

后端 未结 1 508
孤独总比滥情好
孤独总比滥情好 2021-01-19 03:25

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

相关标签:
1条回答
  • 2021-01-19 03:48

    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());
    }
    
    0 讨论(0)
提交回复
热议问题