【发布时间】:2018-09-29 13:07:35
【问题描述】:
在Box中包裹内闭包很容易:
fn add1() -> impl Fn(i32) -> Box<Fn(i32) -> i32> {
|x| Box::new(|y| x + y)
}
但是有必要使用Box吗?在以下代码中:
fn add2() -> ?? {
|x: i32| move |y: i32| x + y
}
我可以将?? 替换为进行代码类型检查的东西吗?
【问题讨论】:
在Box中包裹内闭包很容易:
fn add1() -> impl Fn(i32) -> Box<Fn(i32) -> i32> {
|x| Box::new(|y| x + y)
}
但是有必要使用Box吗?在以下代码中:
fn add2() -> ?? {
|x: i32| move |y: i32| x + y
}
我可以将?? 替换为进行代码类型检查的东西吗?
【问题讨论】:
没有。如您所知,impl Trait 是一种无需装箱即可返回特征实例的机制。
如果你尝试扩展它:
fn add2() -> impl Fn(i32) -> impl Fn(i32) -> i32 {
|x| |y| x + y
}
编译器告诉你:
error[E0562]: `impl Trait` not allowed outside of function and inherent method return types
--> src/lib.rs:9:30
|
9 | fn add2() -> impl Fn(i32) -> impl Fn(i32) -> i32 {
| ^^^^^^^^^^^^^^^^^^^
来自impl Trait RFC,强调我的:
impl Trait只能写在 a 的返回类型中 独立或固有的实现功能,不在特征定义中或 任何非返回类型的位置。他们也可能不会出现在退货中 闭包特征或函数指针的类型,除非它们是 它们是合法返回类型的一部分。
- 最终,我们希望允许在特征中使用该功能
闭包的返回类型是闭包特征的关联类型:
pub trait FnOnce<Args> {
type Output;
extern "rust-call" fn call_once(self, args: Args) -> Self::Output;
}
另见:
【讨论】: