👻

Future TraitのVec

2023/05/21に公開
use std::future::Future;
use std::pin::Pin;

async fn print_x(x: usize) -> i32 {
    println!("x={}", x);
    5
}

async fn print_xy(x: usize, y: usize) -> i32 {
    println!("x={}, y={}", x, y);
    5
}

async fn future_vector() {
    let mut x: Vec<Pin<Box<dyn Future<Output = i32>>>> = vec![];

    x.push(Box::pin(print_x(1)));
    x.push(Box::pin(print_x(2)));
    x.push(Box::pin(print_xy(3, 4)));
    x.push(Box::pin(print_xy(5, 6)));

    for a in x {
        a.await;
    }
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    future_vector().await;
    Ok(())
}

詳細はこちらを参照
関数ポインタの配列も!
https://users.rust-lang.org/t/how-to-handle-a-vector-of-async-function-pointers/39804

Discussion