异步函数 async fn ​

核心概念 ​

async fn 是定义异步函数的语法,编译器会将 async fn 的函数体转换为一个实现了 Future trait 的状态机。async fn foo() -> T 的实际返回类型不是 T,而是 impl Future<Output = T>。调用 async fn 不会执行函数体,只是创建一个 Future 对象。函数体中的代码要到 Future 被 .await 或被运行时 poll 时才会执行。async fn 可以出现在顶层、impl 块中、trait 中(Rust 1.75+)。async fn 内部可以使用 .await 来等待其他 Future。

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

// 基本的 async fn
async fn hello() -> String {
    sleep(Duration::from_millis(50)).await;
    "Hello, async world!".to_string()
}

// 带参数的 async fn
async fn add(a: i32, b: i32) -> i32 {
    a + b
}

// 返回 Result 的 async fn
async fn divide(a: f64, b: f64) -> Result<f64, String> {
    if b == 0.0 {
        Err("除数不能为零".to_string())
    } else {
        Ok(a / b)
    }
}

// 无返回值的 async fn(返回 ())
async fn log(msg: &str) {
    sleep(Duration::from_millis(10)).await;
    println!("[日志] {}", msg);
}

#[tokio::main]
async fn main() {
    println!("{}", hello().await);
    println!("3 + 4 = {}", add(3, 4).await);
    println!("10 / 3 = {:?}", divide(10.0, 3.0).await);
    log("程序启动").await;
}

async fn 的脱糖形式 ​

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

// 这个 async fn:
async fn compute(x: i32) -> i32 {
    sleep(Duration::from_millis(10)).await;
    x * 2
}

// 编译器将其脱糖为大致如下的形式:
fn compute_desugared(x: i32) -> impl Future<Output = i32> {
    async move {
        sleep(Duration::from_millis(10)).await;
        x * 2
    }
}

// 两者在使用上完全等价
#[tokio::main]
async fn main() {
    let a = compute(21).await;
    let b = compute_desugared(21).await;
    println!("async fn: {}", a);        // 42
    println!("脱糖版: {}", b);          // 42

    // async fn 生成的 Future 是一个匿名状态机
    // 每个 .await 点是一个状态转换
    // 编译器在编译时确定状态机大小(零成本抽象)
    println!("compute Future 大小: {} 字节",
        std::mem::size_of_val(&compute(0)));
}

async fn 与引用参数 ​

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

// async fn 可以接受引用参数
// 返回的 Future 的生命周期与引用参数绑定
async fn process(data: &str) -> usize {
    sleep(Duration::from_millis(10)).await;
    data.len()
}

// 上面等价于:
// fn process<'a>(data: &'a str) -> impl Future<Output = usize> + 'a { ... }
// Future 的生命周期与 data 的生命周期绑定
// 在 Future 完成前,data 必须有效

// 多个引用参数
async fn compare(a: &str, b: &str) -> std::cmp::Ordering {
    sleep(Duration::from_millis(10)).await;
    a.len().cmp(&b.len())
}

// 引用参数的限制:不能直接 spawn
// tokio::spawn 要求 'static,引用参数不满足
// 解决方案:先克隆数据再 spawn
async fn process_in_background(data: String) -> usize {
    sleep(Duration::from_millis(10)).await;
    data.len()
}

#[tokio::main]
async fn main() {
    let text = String::from("hello");

    // 直接 await:引用参数没问题
    let len = process(&text).await;
    println!("长度: {}", len);

    // spawn:需要 'static,不能传引用
    // tokio::spawn(process(&text));  // 编译错误

    // 解决方案:克隆后传所有权
    let text_clone = text.clone();
    let handle = tokio::spawn(async move {
        process_in_background(text_clone).await
    });
    println!("spawn 结果: {}", handle.await.unwrap());

    // 原始 text 仍可用
    println!("原始: {}", text);
}

async fn 在 impl 块中 ​

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

struct HttpClient {
    base_url: String,
    timeout_ms: u64,
}

impl HttpClient {
    fn new(base_url: &str) -> Self {
        HttpClient {
            base_url: base_url.to_string(),
            timeout_ms: 5000,
        }
    }

    // impl 块中的 async fn
    async fn get(&self, path: &str) -> Result<String, String> {
        let url = format!("{}{}", self.base_url, path);
        sleep(Duration::from_millis(100)).await;
        Ok(format!("GET {} → 200 OK", url))
    }

    async fn post(&self, path: &str, body: &str) -> Result<String, String> {
        let url = format!("{}{}", self.base_url, path);
        sleep(Duration::from_millis(150)).await;
        Ok(format!("POST {} [{}] → 201 Created", url, body))
    }

    // async fn 可以调用其他 async 方法
    async fn health_check(&self) -> bool {
        match self.get("/health").await {
            Ok(_) => true,
            Err(_) => false,
        }
    }
}

#[tokio::main]
async fn main() {
    let client = HttpClient::new("https://api.example.com");

    // 调用 impl 中的 async 方法
    if client.health_check().await {
        println!("服务健康");
    }

    let response = client.get("/users").await.unwrap();
    println!("{}", response);

    let response = client.post("/users", r#"{"name":"张三"}"#).await.unwrap();
    println!("{}", response);
}

async fn 在 trait 中(Rust 1.75+) ​

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

// Rust 1.75+ 支持 trait 中的 async fn
trait DataSource {
    async fn fetch(&self, key: &str) -> Option<String>;
    async fn store(&self, key: &str, value: &str) -> Result<(), String>;
}

struct MemoryStore {
    data: std::collections::HashMap<String, String>,
}

impl MemoryStore {
    fn new() -> Self {
        MemoryStore {
            data: std::collections::HashMap::new(),
        }
    }
}

impl DataSource for MemoryStore {
    async fn fetch(&self, key: &str) -> Option<String> {
        sleep(Duration::from_millis(10)).await;
        self.data.get(key).cloned()
    }

    async fn store(&self, _key: &str, _value: &str) -> Result<(), String> {
        sleep(Duration::from_millis(10)).await;
        // 注意:这里 self 是不可变引用,实际需要内部可变性
        Ok(())
    }
}

// 使用 trait 的泛型函数
async fn use_source(source: &impl DataSource) {
    match source.fetch("name").await {
        Some(val) => println!("找到: {}", val),
        None => println!("未找到"),
    }
}

#[tokio::main]
async fn main() {
    let store = MemoryStore::new();
    use_source(&store).await;
}

async fn 的组合模式 ​

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

// 顺序调用
async fn sequential() -> Vec<String> {
    let mut results = Vec::new();
    results.push(step("A", 100).await);
    results.push(step("B", 100).await);
    results.push(step("C", 100).await);
    results  // 总耗时 ~300ms
}

// 并发调用
async fn concurrent() -> Vec<String> {
    let (a, b, c) = tokio::join!(
        step("A", 100),
        step("B", 100),
        step("C", 100)
    );
    vec![a, b, c]  // 总耗时 ~100ms
}

async fn step(name: &str, ms: u64) -> String {
    sleep(Duration::from_millis(ms)).await;
    format!("步骤{}", name)
}

// 条件调用
async fn conditional(flag: bool) -> String {
    if flag {
        step("快速", 50).await
    } else {
        step("慢速", 200).await
    }
}

// 重试模式
async fn with_retry<F, Fut, T, E>(f: F, max_retries: u32) -> Result<T, E>
where
    F: Fn() -> Fut,
    Fut: std::future::Future<Output = Result<T, E>>,
    E: std::fmt::Display,
{
    let mut last_err = None;
    for attempt in 1..=max_retries {
        match f().await {
            Ok(val) => return Ok(val),
            Err(e) => {
                println!("  第{}次失败: {}", attempt, e);
                last_err = Some(e);
                if attempt < max_retries {
                    sleep(Duration::from_millis(100 * attempt as u64)).await;
                }
            }
        }
    }
    Err(last_err.unwrap())
}

#[tokio::main]
async fn main() {
    // 顺序 vs 并发
    let start = Instant::now();
    let results = sequential().await;
    println!("顺序: {:?}, {:?}", results, start.elapsed());

    let start = Instant::now();
    let results = concurrent().await;
    println!("并发: {:?}, {:?}\n", results, start.elapsed());

    // 条件调用
    println!("条件: {}", conditional(true).await);

    // 重试
    println!("\n重试模式:");
    use std::sync::atomic::{AtomicU32, Ordering};
    static COUNT: AtomicU32 = AtomicU32::new(0);

    let result = with_retry(|| async {
        let n = COUNT.fetch_add(1, Ordering::SeqCst);
        if n < 2 {
            Err(format!("错误#{}", n))
        } else {
            Ok("成功")
        }
    }, 5).await;
    println!("结果: {:?}", result);
}

基本示例 ​

用 async fn 构建一个异步服务层:

rust
use tokio::time::{sleep, Duration, Instant};
use std::collections::HashMap;

// 数据模型
#[derive(Debug, Clone)]
struct User {
    id: u32,
    name: String,
    email: String,
}

// 异步服务层
struct UserService;

impl UserService {
    // 模拟数据库查询
    async fn find_by_id(id: u32) -> Option<User> {
        sleep(Duration::from_millis(80)).await;
        match id {
            1 => Some(User { id: 1, name: "张三".into(), email: "zhang@example.com".into() }),
            2 => Some(User { id: 2, name: "李四".into(), email: "li@example.com".into() }),
            3 => Some(User { id: 3, name: "王五".into(), email: "wang@example.com".into() }),
            _ => None,
        }
    }

    // 批量查询
    async fn find_many(ids: &[u32]) -> Vec<User> {
        let futures: Vec<_> = ids.iter()
            .map(|&id| Self::find_by_id(id))
            .collect();

        futures::future::join_all(futures).await
            .into_iter()
            .flatten()
            .collect()
    }

    // 验证用户
    async fn validate(user: &User) -> Result<(), String> {
        sleep(Duration::from_millis(30)).await;
        if user.name.is_empty() {
            Err("名称不能为空".into())
        } else if !user.email.contains('@') {
            Err("邮箱格式不正确".into())
        } else {
            Ok(())
        }
    }

    // 组合操作:查找并验证
    async fn find_and_validate(id: u32) -> Result<User, String> {
        let user = Self::find_by_id(id).await
            .ok_or_else(|| format!("用户 {} 不存在", id))?;
        Self::validate(&user).await?;
        Ok(user)
    }
}

// 异步通知服务
struct NotifyService;

impl NotifyService {
    async fn send_email(to: &str, subject: &str) -> Result<(), String> {
        sleep(Duration::from_millis(100)).await;
        println!("  邮件发送到 {}: {}", to, subject);
        Ok(())
    }
}

// 异步业务流程
async fn onboard_user(id: u32) -> Result<String, String> {
    // 步骤1:查找用户
    let user = UserService::find_and_validate(id).await?;
    println!("  找到用户: {:?}", user);

    // 步骤2:并发发送欢迎邮件和记录日志
    let (email_result, _) = tokio::join!(
        NotifyService::send_email(&user.email, "欢迎加入"),
        async {
            sleep(Duration::from_millis(20)).await;
            println!("  记录日志: 用户 {} 已入职", user.name);
        }
    );
    email_result?;

    Ok(format!("{} 入职流程完成", user.name))
}

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

    // 单个用户入职
    println!("=== 用户入职 ===");
    match onboard_user(1).await {
        Ok(msg) => println!("成功: {}\n", msg),
        Err(e) => println!("失败: {}\n", e),
    }

    // 不存在的用户
    match onboard_user(99).await {
        Ok(msg) => println!("成功: {}", msg),
        Err(e) => println!("预期失败: {}\n", e),
    }

    // 批量查询
    println!("=== 批量查询 ===");
    let users = UserService::find_many(&[1, 2, 3, 4, 5]).await;
    for user in &users {
        println!("  {:?}", user);
    }
    println!("找到 {} 个用户", users.len());

    // 并发入职多个用户
    println!("\n=== 并发入职 ===");
    let start = Instant::now();
    let results = futures::future::join_all(
        vec![1, 2, 3].into_iter().map(|id| onboard_user(id))
    ).await;

    for result in &results {
        match result {
            Ok(msg) => println!("  {}", msg),
            Err(e) => println!("  错误: {}", e),
        }
    }
    println!("并发总耗时: {:?}", start.elapsed());
}

常见问题 ​

问题一:async fn 和返回 impl Future 有什么区别?

功能上等价。async fn foo() -> T 就是 fn foo() -> impl Future<Output = T> 的语法糖。async fn 更简洁,函数体直接写异步代码;返回 impl Future 的方式可以在函数体中使用更灵活的控制(比如条件性返回不同的 Future)。

问题二:async fn 可以是递归的吗?

不能直接递归,因为编译器无法确定递归 Future 的大小。需要用 Box::pin 包装返回值,或使用 async_recursion crate 的 #[async_recursion] 宏。

问题三:async fn 能作为 trait 方法吗?

Rust 1.75 开始支持 trait 中的 async fn。在此之前需要用 async-trait crate 的 #[async_trait] 宏来实现。

问题四:async fn 中可以用 std:🧵:sleep 吗?

技术上可以,但不应该。std::thread::sleep 会阻塞执行器线程,影响同一线程上其他异步任务的执行。应该用 tokio::time::sleep 等异步版本。

适用场景 ​

  • 异步服务层:数据库查询、HTTP 请求、缓存操作
  • impl 方法:对象的异步行为
  • trait 方法:定义异步接口(Rust 1.75+)
  • 组合操作:在 async fn 中调用其他 async fn

注意事项 ​

  • async fn 调用只创建 Future,不立即执行
  • 引用参数的 Future 生命周期与引用绑定
  • tokio::spawn 需要 'static Future,不能传引用参数
  • trait 中的 async fn 需要 Rust 1.75+ 或 async-trait crate
  • 不要在 async fn 中使用阻塞操作(std::thread::sleep 等)
  • 递归 async fn 需要 Box::pin 或 async_recursion crate

总结 ​

async fn 是定义异步函数的语法糖,编译器将其转换为返回 impl Future<Output = T> 的函数,函数体被编译为状态机。调用 async fn 只创建 Future,.await 才执行。async fn 可以出现在顶层、impl 块和 trait 中(Rust 1.75+)。引用参数的 Future 生命周期与引用绑定,tokio::spawn 需要 'static 不能传引用。async fn 适合定义异步服务层、对象方法和接口。在 async fn 中应避免阻塞操作,用异步版本代替。多个独立的 async fn 调用可以用 tokio::join! 并发执行。