问题描述
我正在尝试学习异步编程,但这个非常基本的示例不起作用:
I'm trying to learn async programming, but this very basic example doesn't work:
use std::future::Future;
fn main() {
let t = async {
println!("Hello, world!");
};
t.poll();
}
我从规范中读到的所有内容都说这应该可行,但是货物抱怨在impl std::future::Future"中找不到方法poll".我做错了什么?
Everything I've read from the specs says this should work, but cargo complains that method "poll" can't be found in "impl std::future::Future". What am I doing wrong?
推荐答案
poll
有这个签名:
poll
has this signature:
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
以您的方式调用它有两个问题:
There are two problems with calling this in the way you do:
poll
is not implement on a futureFut
, but onPin<&mut Fut>
, so you need to get a pinned reference first.pin_mut!
is often useful, and if the future implementsUnpin
, you can usePin::new
as well.
然而,更大的问题是 poll
需要一个 &mut Context
参数.上下文由异步运行时创建并传递给最外层 future 的 poll
函数.这意味着您不能像那样轮询未来,您需要在异步运行时中才能做到这一点.
The bigger problem however is that poll
takes a &mut Context<'_>
argument. The context is created by the asynchronous runtime and passed in to the poll
function of the outermost future. This means that you can't just poll a future like that, you need to be in an asynchronous runtime to do it.
相反,您可以使用像 tokio
这样的板条箱或 async-std
以运行未来同步上下文:
Instead, you can use a crate like tokio
or async-std
to run a future in a synchronous context:
// 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 {
// ...
})
或者更好的是,您可以使用 #[tokio::main]
或 #[async_std::main]
将您的 main
函数转换为异步函数:
Or even better, you can use #[tokio::main]
or #[async_std::main]
to convert your main
function into an asynchronous function:
// tokio
#[tokio::main]
async fn main() {
// ...
}
// async-std
#[async_std::main]
async fn main() {
// ...
}
这篇关于Rust:方法“轮询"在 `impl std::future::Future` 中找不到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!