【问题标题】:Rust: Method "poll" not found in `impl std::future::Future`Rust:在`impl std::future::Future`中找不到方法“poll”
【发布时间】:2020-04-22 15:42:55
【问题描述】:

我正在尝试学习异步编程,但是这个非常基本的示例不起作用:

use std::future::Future;

fn main() {
    let t = async {
        println!("Hello, world!");
    };
    t.poll();
}

我从规范中读到的所有内容都表明这应该可以工作,但 cargo 抱怨在“impl std::future::Future”中找不到方法“poll”。我做错了什么?

【问题讨论】:

  • 你到底想用你的代码做什么?通常在编写异步应用程序时不会直接使用.poll,而是使用awaitFutureExt 中的方法。
  • 我主要是在学习系统的工作原理。我不能在非异步上下文中使用 await,所以我试图弄清楚如何在非异步上下文中调用异步方法。

标签: rust


【解决方案1】:

poll 有这个签名:

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;

以你的方式调用它有两个问题:

  1. poll 不是在未来的Fut 上实现的,而是在Pin&lt;&amp;mut Fut&gt; 上实现的,所以你需要先获得一个固定的参考。 pin_mut! 经常有用,如果将来实现Unpin,你也可以使用Pin::new

  2. 然而,更大的问题是poll 接受&amp;mut @987654325@&lt;'_&gt; 参数。上下文由异步运行时创建并传递给最外层未来的poll 函数。这意味着您不能像那样只轮询未来,您需要在异步运行时中才能做到这一点。

相反,您可以使用 tokioasync-std 之类的 crate 在同步上下文中运行未来:

// 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 函数转换为异步函数:

// tokio
#[tokio::main]
async fn main() {
  // ...
}

// async-std
#[async_std::main]
async fn main() {
  // ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多