问题描述
我开始阅读有关闭包的。在指南中:
I started reading the Rust guide on closures. From the guide:
有没有一种方法可以显式地编写闭包的类型签名?
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?
推荐答案
否。是否有任何编译器标志可以扩展推断的闭合类型?真正的闭包类型只有编译器才知道,而能够知道给定闭包的具体类型实际上并没有多大用处。您可以指定闭合必须适合的某些形状,但是:
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);
}
在这种情况下,我们说 call_it
接受任何实现特征 Fn
且类型为 u8
且返回类型为的类型 u8
。
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.
从Rust 1.26.0开始,您还可以使用 impl Trait
接受或返回闭包(或任何其他特征)的语法:
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());
}
这篇关于有什么方法可以显式地编写闭包的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!