【问题标题】:Ready or pending future depending on a condition准备好或未决的未来取决于条件
【发布时间】:2022-10-14 02:21:58
【问题描述】:

我需要根据条件将准备好的或待处理的未来保存在变量中。

如果我能做到这一点会很好:

let f = futures::future::ready(true);

但是 API 提供了两个不同的函数,它们具有不同的返回类型,因此,这也不起作用:

let f = if true { futures::future::ready(()) } else { futures::future::pending::<()>() }

我知道我可以为此实现自己的未来,但我想知道是否有办法使if 表达式工作?

【问题讨论】:

  • 你想要的这个未来应该总是准备好还是待定?
  • 当然,有futures::future::Either
  • @SvenMarnach,谢谢!这正是我一直在寻找的。
  • @AleksanderKrauze,是的。

标签: rust rust-futures


【解决方案1】:

您可以使用 futures::future::Either 类型:

use futures::future::Either;
use std::future::{pending, ready, Future};

pub fn pending_or_ready(cond: bool) -> impl Future<Output = ()> {
    if cond {
        Either::Left(ready(()))
    } else {
        Either::Right(pending())
    }
}

(Playground)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-18
    • 2011-08-18
    • 2011-04-18
    • 2016-07-24
    相关资源
    最近更新 更多