You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Rust中根据条件存储Ready或Pending Future?

解决Rust中if分支返回不同Future类型的问题

你遇到的问题核心是:futures::future::ready返回的是Ready<T>类型,futures::future::pending返回的是Pending<T>类型,这是两个完全独立的结构体,Rust要求if/else的所有分支必须返回同一类型,所以直接写会编译报错。

不用自己实现Future,有两种简单的方法解决:

方法1:用Either枚举(推荐,无堆分配)

futures库自带的Either是专门用来处理这种“二选一”的不同类型但实现同一 trait 的场景,它会把两个Future包装成同一个枚举类型,同时本身也实现了Future trait,可以直接await。

代码示例:

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

let f = if true {
    Either::Left(ready(()))
} else {
    Either::Right(pending::<()>())
};

方法2:用装箱的Trait Object(堆分配)

把两个Future都装箱成Box<dyn Future<Output = T>>,强制统一类型。这种方法需要堆内存分配,性能略逊于Either,但适合类型更复杂的场景。

代码示例:

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

let f: Box<dyn Future<Output = ()>> = if true {
    Box::new(ready(()))
} else {
    Box::new(pending::<()>())
};

内容的提问来源于stack exchange,提问作者nicolai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 17:40:54