Rust:方法“轮询"在 `impl std::future::Future` 中找不到

编程入门 行业动态 更新时间:2024-10-09 22:23:16
本文介绍了Rust:方法“轮询"在 `impl std::future::Future` 中找不到的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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 不是在未来的 Fut 上实现的,而是在 Pin 上实现的,所以你需要首先获得固定参考.pin_mut! 通常很有用,并且如果未来实现 Unpin,你可以使用Pin::new 也是.

  • poll is not implement on a future Fut, but on Pin<&mut Fut>, so you need to get a pinned reference first. pin_mut! is often useful, and if the future implements Unpin, you can use Pin::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` 中找不到

    本文发布于:2023-11-25 21:23:31,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1631399.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:中找   方法   quot   轮询   Rust

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!