Z
ZHANK
进阶技巧

async/await 异步

async fn/block、Future trait、.await、tokio 运行时简介

async/await 异步

Rust 的异步是零成本的——async fn 返回 Future.await 等待完成。需要运行时(如 tokio)来轮询执行。

学完本章你将: 掌握 async fn、Future、.await、tokio 运行时简介。


async 函数

rust
// Cargo.toml:
// [dependencies]
// tokio = { version = "1", features = ["full"] }

async fn fetch_data(url: &str) -> Result<String, reqwest::Error> {
    let resp = reqwest::get(url).await?;
    resp.text().await
}

#[tokio::main]  // tokio 运行时
async fn main() {
    match fetch_data("https://httpbin.org/get").await {
        Ok(data) => println!("{}", &data[..100]),
        Err(e) => println!("错误: {}", e),
    }
}

并发执行

rust
#[tokio::main]
async fn main() {
    let (result1, result2) = tokio::join!(
        fetch_data("https://httpbin.org/delay/1"),
        fetch_data("https://httpbin.org/delay/1"),
    );
    // 两个请求并发——总共 ~1 秒
}

async 原理

rust
// async fn 返回的是 Future——一个状态机
async fn hello() -> &'static str {
    "hello"
}

// 等价于(简化):
// fn hello() -> impl Future<Output = &'static str> {
//     async { "hello" }
// }

// .await 会挂起当前任务,让运行时去执行其他 Future

💡 Rust 的 async 不提供运行时——你需要 tokio、async-std 或 smol。标准库只提供 Future trait 定义。