考虑以下返回异步块的闭包:

|entity: &mut Entity| async move {
    entity.foo().await;
}

是否可以在枚举中键入Erase并存储该闭包,而不指定该枚举的泛型类型或生存期?请考虑以下MWE:

use std::future::Future;

struct Entity;
impl Entity {
    async fn foo(&mut self) {} 
}

fn main() {
    erase_and_store(|entity: &mut Entity| async move {
        entity.foo().await;
    });
}

fn erase_and_store<'a, C, F>(closure: C) -> Task where
    C: FnOnce(&'a mut Entity) -> F,
    F: Future<Output = ()> + 'a {
    
    Task::Variant(/* TODO convert closure to something that can be stored */)
}

enum Task {
    Variant(/* TODO store closure */)
}

我try 了几种不同的方法,但似乎即使我将所有东西都放在盒装的特征对象之后,我也无法阻止这个泛型生存期'a泄漏到我的Task枚举.

type AnyFuture<'a> = Box<dyn Future<Output = ()> + 'a>;
type AnyClosure<'a> = Box<dyn FnOnce(&'a mut Entity) -> AnyFuture<'a>>;

enum Task {
    Variant(AnyClosure) // requires <'a>
}

推荐答案

你想要的是一个排名更高的人生:

type AnyFuture<'a> = Pin<Box<dyn Future<Output = ()> + 'a>>;
type AnyClosure = Box<dyn for<'a> FnOnce(&'a mut Entity) -> AnyFuture<'a>>;

这是可以省略的:

type AnyFuture<'a> = Pin<Box<dyn Future<Output = ()> + 'a>>;
type AnyClosure = Box<dyn FnOnce(&mut Entity) -> AnyFuture<'_>>;

Rust相关问答推荐

MutexGuard中的过滤载体不需要克隆

"value is never read警告似乎不正确.我应该忽略它吗?

integer cast as pointer是什么意思

是否可以使用Rust宏来构建元组的项?

为什么';t std::cell::ref使用引用而不是非空?

异步函数返回的future 生存期

装箱特性如何影响传递给它的参数的生命周期 ?(举一个非常具体的例子)

减少指示ProgressBar在Rust中的开销

我可以解构self 参数吗?

如何在 Rust 中将函数项变成函数指针

将引用移动到线程中

If let expression within .iter().any

无法把握借来的价值不够长寿,请解释

在 FFI 的上下文中,未初始化是什么意思?

你能告诉我如何在 Rust 中使用定时器吗?

在 RefCell 上borrow

在 Rust 中为泛型 struct 编写一次特征绑定

如何用另一个变量向量置换 rust simd 向量?

如何将 while 循环内的用户输入添加到 Rust 中的向量?

传递 Option<&mut T> 时何时需要 mut