有什么方法可以显式地编写闭包的类型? [英] Is there any way to explicitly write the type of a closure?

查看:58
本文介绍了有什么方法可以显式地编写闭包的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始阅读有关闭包的锈迹指南。在指南中:

I started reading the Rust guide on closures. From the guide:


这是因为在Rust中,每个闭包都有其自己的唯一类型。因此,不仅具有不同签名的闭包具有不同的类型,而且具有相同签名的不同闭包也具有不同的类型。

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?

推荐答案

否。是否有任何编译器标志可以扩展推断的闭合类型?真正的闭包类型只有编译器才知道,而能够知道给定闭包的具体类型实际上并没有多大用处。您可以指定闭合必须适合的某些形状,但是:

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

这篇关于有什么方法可以显式地编写闭包的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆