asynchronous - 预期为 `async` block ,发现了不同的 `async` block

标签 asynchronous rust rust-tokio

我试图使用 futures::future::select_ok (playground):

use std::time::Duration;
use tokio; // 1.16.1
use futures; // 0.3.19

#[tokio::main]
async fn main() {
    let first_future = async {
        tokio::time::sleep(Duration::from_secs(1)).await;
        Ok(3)
    };
    let second_future = async {
        tokio::time::sleep(Duration::from_millis(100)).await;
        Err(())
    };
    let third_future = async {
        tokio::time::sleep(Duration::from_secs(300)).await;
        Ok(3)
    };
    futures::future::select_ok(&[first_future,second_future.await,third_future]).await;
}

并遇到错误:

error[E0308]: mismatched types
  --> src/main.rs:19:47
   |
7  |       let first_future = async {
   |  ______________________________-
8  | |         tokio::time::sleep(Duration::from_secs(1)).await;
9  | |         Ok(3)
10 | |     };
   | |_____- the expected `async` block
...
19 |       futures::future::select_ok(&[first_future,second_future.await,third_future]).await;
   |                                                 ^^^^^^^^^^^^^^^^^^^ expected opaque type, found enum `Result`
   |
   = note: expected opaque type `impl futures::Future<Output = [async output]>`
                     found enum `Result<_, ()>`

For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground` due to previous error

我不知道我在这里缺少什么,非常感谢任何帮助。

最佳答案

每个异步 block 都被视为不同的类型,就像闭包一样(IIRC)。他们都实现了Future ,所以您可能想要实际动态地调度它们。为此,您需要将它们包装在 Pin<Box> 中:

use futures;
use std::future::Future;
use std::pin::Pin;
use std::time::Duration;
use tokio; // 1.16.1 // 0.3.19

#[tokio::main]
async fn main() {
    let first_future = async {
        tokio::time::sleep(Duration::from_secs(1)).await;
        Ok(3)
    };
    let second_future = async {
        tokio::time::sleep(Duration::from_millis(100)).await;
        Err(())
    };
    let third_future = async {
        tokio::time::sleep(Duration::from_secs(300)).await;
        Ok(3)
    };
    let futures: [Pin<Box<dyn Future<Output = Result<usize, ()>>>>; 3] = [
        Box::pin(first_future),
        Box::pin(second_future),
        Box::pin(third_future),
    ];
    futures::future::select_ok(futures).await;
}

Playground

关于asynchronous - 预期为 `async` block ,发现了不同的 `async` block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71070434/

相关文章:

ios - 在执行 AFNetwork 请求之前执行 UI 更改

java - CompletableFuture 的问题 - 不等待所有 URL 被调用

rust - 调用 tokio::spawn 时如何设置 `self` 的正确生命周期?

rust - web_sys crate 是如何工作的?

rust - 找不到tokio::main宏?

rust - 如何解决错误 "thread ' main' paniced at 'no current reactor'”?

java - 使用异步 TaskManager 处理作业/步骤异常

c# - 返回任务的方法的不同实现

rust - 为什么以下宏在被调用时会期望使用分号?

rust - Cargo.toml中的[dependencies]和[dependencies.dependency-name]有什么区别?