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

感情迁移 提交于 2019-12-10 15:49:52

问题


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?


回答1:


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());
}


来源:https://stackoverflow.com/questions/29191170/is-there-any-way-to-explicitly-write-the-type-of-a-closure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!