Rust中类似Python asyncio.Future(含set_result())的结构体查询
实现类似Python asyncio.Future的Rust方案
有几个成熟的工具crate可以满足你的需求,无需自己手动实现:
1. futures crate 的 oneshot 通道
futures crate 提供的oneshot::channel是最常用的方案。它会生成一对Sender和Receiver,其中Receiver本身就是一个Future,会一直处于pending状态,直到Sender调用send方法传递结果(对应Python的set_result)。
示例代码:
use futures::channel::oneshot; #[tokio::main] async fn main() { let (sender, receiver) = oneshot::channel(); // 在另一个任务中设置结果 tokio::spawn(async move { sender.send("Hello from future!").unwrap(); }); // 等待结果返回 let result = receiver.await.unwrap(); println!("{}", result); }
2. tokio crate 的 oneshot 通道
如果你基于Tokio运行时开发,tokio::sync::oneshot是更适配的选择,逻辑和futures的实现一致,API使用起来几乎没有区别。
3. 封装成更贴近Python Future的API
如果想要更接近Python asyncio.Future的调用方式(比如直接调用.set_result()的对象),可以基于oneshot::Sender做简单封装,避免自己处理底层同步逻辑:
use futures::channel::oneshot; struct RustFuture<T> { sender: Option<oneshot::Sender<T>>, } impl<T> RustFuture<T> { fn new() -> (Self, impl std::future::Future<Output = T>) { let (sender, receiver) = oneshot::channel(); (Self { sender: Some(sender) }, receiver) } // 对应Python的set_result方法 fn set_result(&mut self, value: T) -> Result<(), T> { self.sender.take().map_or(Err(value), |s| s.send(value)) } } // 使用示例 #[tokio::main] async fn main() { let (mut future, receiver) = RustFuture::new(); tokio::spawn(async move { future.set_result(42).unwrap(); }); let result = receiver.await; println!("最终结果: {}", result); }
这些方案都基于维护成熟的官方/社区crate,比自己实现更安全可靠,也能避免不必要的限制和潜在bug。
内容的提问来源于stack exchange,提问作者wallefan
相关产品推荐
相关产品推荐

