有什么办法可以显式地写出闭包的类型吗?
Is there any way to explicitly write the type of a closure?
我开始阅读有关闭包的 Rust 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.
有没有办法显式地写出闭包的类型签名?是否有扩展推断闭包类型的编译器标志?
没有。闭包的真实类型只有编译器知道,知道给定闭包的具体类型实际上并没有多大用处。您可以指定闭包必须适合的某些 "shapes",但是:
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
并且 return 类型为 u8
。然而,许多闭包和自由函数可以实现该特性。
从 Rust 1.26.0 开始,您还可以使用 impl Trait
语法来接受或 return 闭包(或任何其他特征):
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());
}
我开始阅读有关闭包的 Rust 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.
有没有办法显式地写出闭包的类型签名?是否有扩展推断闭包类型的编译器标志?
没有。闭包的真实类型只有编译器知道,知道给定闭包的具体类型实际上并没有多大用处。您可以指定闭包必须适合的某些 "shapes",但是:
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
并且 return 类型为 u8
。然而,许多闭包和自由函数可以实现该特性。
从 Rust 1.26.0 开始,您还可以使用 impl Trait
语法来接受或 return 闭包(或任何其他特征):
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());
}