异步块 async ​

核心概念 ​

异步块 async { ... } 是一种内联创建 Future 的方式,不需要定义一个单独的 async fn。异步块的值是一个实现了 Future 的匿名类型,和 async fn 一样是惰性的——创建时不会执行,只有被 .await 或被运行时 poll 时才执行。异步块可以捕获外部变量(类似闭包),默认按引用捕获,加 move 可以按值捕获。异步块的最后一个表达式就是 Future 的输出值。

rust
use tokio::time::{sleep, Duration};

#[tokio::main]
async fn main() {
    // 基本异步块
    let future = async {
        sleep(Duration::from_millis(100)).await;
        42  // 最后一个表达式是 Future 的输出
    };

    // 异步块创建后不会执行
    println!("Future 已创建");

    // .await 触发执行
    let result = future.await;
    println!("结果: {}", result);

    // 直接 await 一个异步块(创建并立即等待)
    let msg = async {
        "内联异步块的结果"
    }.await;
    println!("{}", msg);
}

async 块与 async fn 的对比 ​

rust
use tokio::time::{sleep, Duration};

// async fn:独立的异步函数
async fn compute_fn(x: i32) -> i32 {
    sleep(Duration::from_millis(50)).await;
    x * 2
}

#[tokio::main]
async fn main() {
    // async fn 调用
    let result = compute_fn(21).await;
    println!("async fn: {}", result);

    // async 块:内联定义,可以捕获外部变量
    let x = 21;
    let result = async {
        sleep(Duration::from_millis(50)).await;
        x * 2  // 直接使用外部变量 x
    }.await;
    println!("async 块: {}", result);

    // async 块适合一次性使用的简单异步逻辑
    // async fn 适合可复用的异步函数
}
特性async fnasync { }
定义位置函数级别表达式级别
参数通过函数参数传入捕获外部变量
复用性可多次调用一次性使用
命名有函数名匿名
适用场景独立的可复用异步逻辑内联的一次性异步操作

async move 块 ​

rust
use tokio::time::{sleep, Duration};

#[tokio::main]
async fn main() {
    // === 默认按引用捕获 ===
    let data = String::from("hello");

    let future = async {
        println!("借用: {}", data);  // 借用 data
    };
    future.await;
    println!("data 仍可用: {}", data);  // data 没被移走

    // === async move:按值捕获(移动所有权)===
    let data = String::from("world");

    let future = async move {
        println!("拥有: {}", data);  // data 被移入异步块
    };
    future.await;
    // println!("{}", data);  // 编译错误:data 已被移走

    // === move 对 Copy 类型的影响 ===
    let count = 10;  // i32 是 Copy

    let future = async move {
        println!("count: {}", count);  // 复制进来
    };
    future.await;
    println!("count 仍可用: {}", count);  // Copy 类型不受影响

    // === 需要 move 的场景:将 Future 传递到其他地方 ===
    let name = String::from("Rust");

    // tokio::spawn 需要 'static Future,必须用 move
    let handle = tokio::spawn(async move {
        sleep(Duration::from_millis(50)).await;
        format!("Hello, {}!", name)
    });

    let result = handle.await.unwrap();
    println!("{}", result);
}

async 块的类型和存储 ​

rust
use std::future::Future;
use tokio::time::{sleep, Duration};

// async 块的类型是匿名的,不能直接写出来
// 但可以用 impl Future 或 Box<dyn Future> 来引用

// 用 impl Future 作为变量类型(需要在函数返回值中)
fn create_future(x: i32) -> impl Future<Output = i32> {
    async move {
        sleep(Duration::from_millis(50)).await;
        x * 2
    }
}

// 用 Box<dyn Future> 存储不同的异步块
fn choose_future(fast: bool) -> Box<dyn Future<Output = String> + Unpin> {
    if fast {
        Box::new(Box::pin(async {
            sleep(Duration::from_millis(50)).await;
            "快速路径".to_string()
        }))
    } else {
        Box::new(Box::pin(async {
            sleep(Duration::from_millis(200)).await;
            "慢速路径".to_string()
        }))
    }
}

#[tokio::main]
async fn main() {
    // impl Future
    let result = create_future(21).await;
    println!("impl Future: {}", result);

    // 在 Vec 中存储多个 async 块(需要 Box + Pin)
    let futures: Vec<std::pin::Pin<Box<dyn Future<Output = i32>>>> = vec![
        Box::pin(async { 1 + 1 }),
        Box::pin(async { 2 + 2 }),
        Box::pin(async { 3 + 3 }),
    ];

    let results = futures::future::join_all(futures).await;
    println!("批量结果: {:?}", results);

    // async 块的大小取决于捕获的变量
    let small = async { 42 };
    let big_data = vec![0u8; 1000];
    let large = async move { big_data.len() };
    println!("小 Future: {} 字节", std::mem::size_of_val(&small));
    println!("大 Future: {} 字节", std::mem::size_of_val(&large));
}

async 块中的控制流 ​

rust
use tokio::time::{sleep, Duration};

#[tokio::main]
async fn main() {
    // === 异步块中的 if-else ===
    let condition = true;
    let result = async {
        if condition {
            sleep(Duration::from_millis(50)).await;
            "条件为真"
        } else {
            sleep(Duration::from_millis(100)).await;
            "条件为假"
        }
    }.await;
    println!("if-else: {}", result);

    // === 异步块中的循环 ===
    let sum = async {
        let mut total = 0;
        for i in 1..=5 {
            sleep(Duration::from_millis(20)).await;
            total += i;
        }
        total
    }.await;
    println!("循环求和: {}", sum);

    // === 异步块中的 ? 操作符 ===
    // 注意:异步块的类型由最后一个表达式决定
    let result: Result<String, String> = async {
        let step1 = Ok::<_, String>("步骤1".to_string())?;
        sleep(Duration::from_millis(30)).await;
        let step2 = Ok::<_, String>("步骤2".to_string())?;
        Ok(format!("{} → {}", step1, step2))
    }.await;
    println!("Result: {:?}", result);

    // === 嵌套异步块 ===
    let result = async {
        let inner = async {
            sleep(Duration::from_millis(30)).await;
            "内层"
        }.await;

        format!("外层包含: {}", inner)
    }.await;
    println!("嵌套: {}", result);
}

基本示例 ​

用异步块实现并发任务管理:

rust
use tokio::time::{sleep, Duration, Instant};
use std::future::Future;
use std::pin::Pin;

#[tokio::main]
async fn main() {
    let start = Instant::now();

    // === 用异步块创建多个并发任务 ===
    println!("=== 并发任务 ===");

    let task_a = async {
        sleep(Duration::from_millis(200)).await;
        println!("  [{:>4}ms] 任务A 完成", start.elapsed().as_millis());
        "数据A"
    };

    let task_b = async {
        sleep(Duration::from_millis(150)).await;
        println!("  [{:>4}ms] 任务B 完成", start.elapsed().as_millis());
        "数据B"
    };

    let task_c = async {
        sleep(Duration::from_millis(100)).await;
        println!("  [{:>4}ms] 任务C 完成", start.elapsed().as_millis());
        "数据C"
    };

    // join! 并发执行所有异步块
    let (a, b, c) = tokio::join!(task_a, task_b, task_c);
    println!("结果: {}, {}, {}", a, b, c);
    println!("总耗时: {:?}\n", start.elapsed());

    // === 用异步块配合 spawn ===
    println!("=== spawn 异步块 ===");
    let start = Instant::now();

    let handles: Vec<_> = (0..5).map(|i| {
        tokio::spawn(async move {
            let delay = 50 * (i as u64 + 1);
            sleep(Duration::from_millis(delay)).await;
            format!("任务{} ({}ms)", i, delay)
        })
    }).collect();

    for handle in handles {
        let result = handle.await.unwrap();
        println!("  {}", result);
    }
    println!("总耗时: {:?}\n", start.elapsed());

    // === 异步块作为条件性操作 ===
    println!("=== 条件性异步操作 ===");

    async fn process(data: &str, validate: bool) -> Result<String, String> {
        // 用异步块包装可选的验证步骤
        if validate {
            let valid = async {
                sleep(Duration::from_millis(50)).await;
                !data.is_empty()
            }.await;

            if !valid {
                return Err("验证失败".to_string());
            }
        }

        // 主处理逻辑
        let result = async {
            sleep(Duration::from_millis(100)).await;
            format!("[已处理] {}", data.to_uppercase())
        }.await;

        Ok(result)
    }

    println!("  带验证: {:?}", process("hello", true).await);
    println!("  不验证: {:?}", process("world", false).await);
    println!("  空数据: {:?}", process("", true).await);

    // === 动态创建异步块集合 ===
    println!("\n=== 动态异步集合 ===");
    let items = vec!["苹果", "香蕉", "橙子", "葡萄", "西瓜"];

    let futures: Vec<Pin<Box<dyn Future<Output = String>>>> = items.iter()
        .enumerate()
        .map(|(i, &item)| {
            Box::pin(async move {
                sleep(Duration::from_millis(30 * (i as u64 + 1))).await;
                format!("#{}: {}", i + 1, item)
            }) as Pin<Box<dyn Future<Output = String>>>
        })
        .collect();

    let results = futures::future::join_all(futures).await;
    for r in &results {
        println!("  {}", r);
    }
}

常见问题 ​

问题一:async 块和闭包有什么区别?

闭包创建的是可调用的对象(实现 Fn/FnMut/FnOnce),async 块创建的是 Future 对象(实现 Future)。闭包调用后立即执行,async 块创建后需要被 .await 才执行。如果需要"返回 Future 的闭包",可以写 || async { ... } 或 move || async move { ... }。

问题二:async 块需要 move 吗?

如果异步块会被传给 tokio::spawn 或存储到需要 'static 的地方,需要 async move。如果只是在当前作用域内 .await,通常不需要 move。

问题三:async 块可以有返回类型标注吗?

不能直接标注,但可以通过最后一个表达式的类型来隐式确定。如果需要明确返回 Result,确保所有分支返回相同类型即可。

问题四:async 块的 Future 可以存到 Vec 里吗?

可以,但需要用 Box::pin() 包装,因为不同 async 块的类型不同(匿名类型),需要用 trait object 统一类型:Vec<Pin<Box<dyn Future<Output = T>>>>。

适用场景 ​

  • 内联异步操作:不值得定义单独函数的简单异步逻辑
  • tokio::spawn:创建要 spawn 的异步任务
  • tokio::join!:并发执行多个互不相关的异步操作
  • 条件性异步:根据条件选择不同的异步路径

注意事项 ​

  • 异步块是惰性的,创建后不会执行
  • 默认按引用捕获变量,async move 按值捕获
  • 最后一个表达式是 Future 的输出值
  • 异步块的类型是匿名的,存储需要用 Box::pin
  • tokio::spawn 需要 'static Future,通常要 async move
  • 异步块中可以使用 .await、?、循环等控制流

总结 ​

async { ... } 创建一个内联的匿名 Future,和 async fn 一样是惰性的。异步块可以捕获外部变量(默认借用,async move 按值移动)。最后一个表达式决定 Future 的输出值。异步块适合一次性使用的简单异步逻辑,常配合 tokio::join!(并发执行)和 tokio::spawn(后台任务)使用。异步块的类型是匿名的,存储到集合中需要用 Pin<Box<dyn Future<Output = T>>>。tokio::spawn 要求 'static Future,需要使用 async move。异步块内可以正常使用 .await、? 操作符和各种控制流语句。