我正在尝试学习异步编程,但是这个非常基本的示例不起作用:
use std::future::Future;
fn main() {
let t = async {
println!("Hello, world!");
};
t.poll();
}
Run Code Online (Sandbox Code Playgroud)
我从规范中读到的所有内容都说这应该有效,但是货物抱怨在“impl std::future::Future”中找不到方法“poll”。我究竟做错了什么?
poll 有这个签名:
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
Run Code Online (Sandbox Code Playgroud)
以您的方式调用它有两个问题:
poll不是在 futureFut上实现,而是在 上实现Pin<&mut Fut>,因此您需要先获得固定引用。pin_mut!通常很有用,如果将来实现Unpin,您也可以使用Pin::new。
然而,更大的问题是poll需要争论。上下文由异步运行时创建并传递给最外层 future的函数。这意味着您不能像这样轮询未来,您需要在异步运行时中才能做到这一点。&mut Context<'_>poll
相反,您可以使用类似tokio或async-std在同步上下文中运行未来的板条箱:
// tokio
use tokio::runtime::Runtime;
let runtime = Runtime::new().unwrap();
let result = runtime.block_on(async {
// ...
});
// async-std
let result = async_std::task::block_on(async {
// ...
})
Run Code Online (Sandbox Code Playgroud)
或者更好的是,您可以使用#[tokio::main]或#[async_std::main]将您的main函数转换为异步函数:
// tokio
#[tokio::main]
async fn main() {
// ...
}
// async-std
#[async_std::main]
async fn main() {
// ...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1380 次 |
| 最近记录: |