Future Trait ​

核心概念 ​

Future 是 Rust 异步编程的核心 trait,定义在 std::future 模块中。它代表一个可能尚未完成的异步计算。Future trait 只有一个必须实现的方法 poll,该方法接收 Pin<&mut Self> 和 &mut Context<'_> 两个参数,返回 Poll<Self::Output>。Poll 枚举有两个变体:Ready(T) 表示计算完成,值为 T;Pending 表示计算尚未完成,稍后再来轮询。每次调用 async fn 时,编译器会自动生成一个实现了 Future 的匿名状态机类型,开发者通常不需要手动实现 Future,但理解它的工作原理对掌握异步编程至关重要。

rust
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};

// Future trait 的定义(标准库中的简化版)
// pub trait Future {
//     type Output;
//     fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
// }

// Poll 枚举的定义
// pub enum Poll<T> {
//     Ready(T),    // 完成,返回结果
//     Pending,     // 未完成,稍后再轮询
// }

// 手动实现一个简单的 Future:立即就绪
struct ReadyFuture {
    value: Option<i32>,
}

impl Future for ReadyFuture {
    type Output = i32;

    fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<i32> {
        // 取出值并返回 Ready
        match self.value.take() {
            Some(v) => Poll::Ready(v),
            None => panic!("Future 已经完成,不应再被 poll"),
        }
    }
}

#[tokio::main]
async fn main() {
    let future = ReadyFuture { value: Some(42) };
    let result = future.await;  // .await 内部调用 poll
    println!("结果: {}", result);
}

poll 方法的工作流程 ​

rust
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};

// 一个需要被轮询多次才能完成的 Future
struct CountdownFuture {
    remaining: u32,
}

impl CountdownFuture {
    fn new(count: u32) -> Self {
        CountdownFuture { remaining: count }
    }
}

impl Future for CountdownFuture {
    type Output = String;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<String> {
        if self.remaining == 0 {
            // 计算完成
            Poll::Ready("倒计时完成!".to_string())
        } else {
            println!("  还剩 {} 次", self.remaining);
            self.remaining -= 1;

            // 通知运行时:这个 Future 可以被再次 poll
            // Waker 是关键——没有它,运行时不知道什么时候该再次轮询
            cx.waker().wake_by_ref();

            Poll::Pending
        }
    }
}

#[tokio::main]
async fn main() {
    println!("开始倒计时:");
    let result = CountdownFuture::new(5).await;
    println!("{}", result);
}

async fn 生成的 Future ​

rust
use std::future::Future;

// async fn 实际上返回一个编译器生成的 Future 类型
async fn compute(x: i32, y: i32) -> i32 {
    x + y
}

// 上面的 async fn 等价于:
fn compute_desugared(x: i32, y: i32) -> impl Future<Output = i32> {
    async move { x + y }
}

// 带 await 的 async fn 会生成更复杂的状态机
async fn multi_step() -> String {
    let a = compute(1, 2).await;  // 状态1:等待 compute
    let b = compute(3, 4).await;  // 状态2:等待 compute
    format!("{} + {} = {}", a, b, a + b)  // 状态3:完成
}

// 编译器大致会生成类似这样的状态机:
// enum MultiStepFuture {
//     State0 { /* 初始状态,准备调用第一个 compute */ },
//     State1 { a: i32, /* 等待第二个 compute */ },
//     State2 { a: i32, b: i32, /* 准备返回结果 */ },
//     Done,
// }

#[tokio::main]
async fn main() {
    let result = multi_step().await;
    println!("{}", result);

    // async fn 返回的 Future 的大小取决于需要保存的状态
    println!("compute Future 大小: {} 字节", std::mem::size_of_val(&compute(1, 2)));
    println!("multi_step Future 大小: {} 字节", std::mem::size_of_val(&multi_step()));
}

手动实现一个延迟 Future ​

rust
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Instant;

// 一个在指定时间后完成的 Future
struct Delay {
    target: Instant,
    registered: bool,
}

impl Delay {
    fn new(duration: std::time::Duration) -> Self {
        Delay {
            target: Instant::now() + duration,
            registered: false,
        }
    }
}

impl Future for Delay {
    type Output = ();

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
        if Instant::now() >= self.target {
            // 时间到了,返回 Ready
            Poll::Ready(())
        } else {
            // 时间还没到
            // 在实际运行时中,这里应该注册一个定时器
            // 定时器到期时调用 waker 唤醒这个 Future
            // 这里简单地立即请求再次轮询(不高效,仅用于演示)
            if !self.registered {
                self.registered = true;
            }
            cx.waker().wake_by_ref();
            Poll::Pending
        }
    }
}

#[tokio::main]
async fn main() {
    println!("等待 500ms...");
    let start = Instant::now();
    Delay::new(std::time::Duration::from_millis(500)).await;
    println!("完成,实际耗时: {:?}", start.elapsed());
}

Future 的组合 ​

rust
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};

// 将两个 Future 顺序组合
struct ThenFuture<A, B, F>
where
    A: Future,
    F: FnOnce(A::Output) -> B,
    B: Future,
{
    state: ThenState<A, B, F>,
}

enum ThenState<A, B, F>
where
    A: Future,
    F: FnOnce(A::Output) -> B,
    B: Future,
{
    First(A, Option<F>),   // 等待第一个 Future
    Second(B),              // 等待第二个 Future
    Done,
}

impl<A, B, F> Future for ThenFuture<A, B, F>
where
    A: Future + Unpin,
    B: Future + Unpin,
    F: FnOnce(A::Output) -> B + Unpin,
{
    type Output = B::Output;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<B::Output> {
        loop {
            match &mut self.state {
                ThenState::First(a, f) => {
                    match Pin::new(a).poll(cx) {
                        Poll::Ready(val) => {
                            let func = f.take().unwrap();
                            let b = func(val);
                            self.state = ThenState::Second(b);
                            // 继续循环,poll 第二个 Future
                        }
                        Poll::Pending => return Poll::Pending,
                    }
                }
                ThenState::Second(b) => {
                    return Pin::new(b).poll(cx);
                }
                ThenState::Done => panic!("poll after done"),
            }
        }
    }
}

// 实际开发中,用 async/await 组合 Future 更简单:
async fn combined() -> String {
    let a = async { 10 }.await;
    let b = async move { a * 2 }.await;
    format!("结果: {}", b)
}

#[tokio::main]
async fn main() {
    // 用 async/await 组合(推荐)
    let result = combined().await;
    println!("{}", result);

    // 用标准库提供的组合方式
    let result = async {
        let x = async { 5 }.await;
        let y = async { x + 10 }.await;
        y
    }.await;
    println!("组合结果: {}", result);
}

基本示例 ​

实现一个自定义的超时 Future 来理解 Future trait 的工作机制:

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

// 带超时的 Future 包装器
struct Timeout<F: Future> {
    future: Pin<Box<F>>,
    deadline: Instant,
    expired: bool,
}

impl<F: Future> Timeout<F> {
    fn new(future: F, duration: Duration) -> Self {
        Timeout {
            future: Box::pin(future),
            deadline: Instant::now() + duration,
            expired: false,
        }
    }
}

impl<F: Future> Future for Timeout<F> {
    type Output = Result<F::Output, &'static str>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        // 先检查内部 Future 是否完成
        match self.future.as_mut().poll(cx) {
            Poll::Ready(val) => return Poll::Ready(Ok(val)),
            Poll::Pending => {}
        }

        // 检查是否超时
        if Instant::now() >= self.deadline {
            Poll::Ready(Err("超时"))
        } else {
            // 注册唤醒,确保稍后会被再次 poll
            cx.waker().wake_by_ref();
            Poll::Pending
        }
    }
}

async fn slow_operation() -> String {
    sleep(Duration::from_millis(300)).await;
    "操作完成".to_string()
}

async fn fast_operation() -> String {
    sleep(Duration::from_millis(50)).await;
    "快速完成".to_string()
}

#[tokio::main]
async fn main() {
    // 测试:操作在超时前完成
    let result = Timeout::new(
        fast_operation(),
        Duration::from_millis(200)
    ).await;
    println!("快速操作: {:?}", result);  // Ok("快速完成")

    // 测试:操作超时
    let result = Timeout::new(
        slow_operation(),
        Duration::from_millis(100)
    ).await;
    println!("慢速操作: {:?}", result);  // Err("超时")

    // 实际开发中用 tokio::time::timeout 更方便
    println!("\n=== tokio::time::timeout ===");

    match tokio::time::timeout(Duration::from_millis(200), fast_operation()).await {
        Ok(result) => println!("成功: {}", result),
        Err(_) => println!("超时"),
    }

    match tokio::time::timeout(Duration::from_millis(100), slow_operation()).await {
        Ok(result) => println!("成功: {}", result),
        Err(_) => println!("超时"),
    }

    // Future 的大小
    println!("\n=== Future 大小 ===");
    println!("fast_operation: {} 字节", std::mem::size_of_val(&fast_operation()));
    println!("slow_operation: {} 字节", std::mem::size_of_val(&slow_operation()));

    // Future 是零成本抽象
    // 编译器在编译时确定状态机大小,不需要堆分配
    // 除非用 Box::pin 或 Box<dyn Future>
}

常见问题 ​

问题一:为什么 poll 需要 Pin<&mut Self>?

Pin 保证 Future 在内存中不会被移动。这对于跨 await 点保存引用的 Future 很重要——如果 Future 被移动了,内部的自引用指针就会失效。大多数手动实现的简单 Future 可以实现 Unpin(表示可以安全移动),编译器生成的 Future 可能包含自引用所以需要 Pin。

问题二:Waker 是什么?

Waker 是运行时提供的唤醒机制。当 Future 返回 Pending 时,应该在合适的时机(如 IO 就绪、定时器到期)调用 Waker 来通知运行时重新 poll 这个 Future。如果不调用 Waker,运行时不知道什么时候该再次轮询,Future 就会"沉睡"。

问题三:需要手动实现 Future 吗?

大多数时候不需要。async fn 和 async { } 会自动生成 Future 实现。只在编写底层库、自定义运行时、或需要精细控制状态机行为时才需要手动实现。

问题四:Future trait 和 JavaScript 的 Promise 有什么区别?

Rust 的 Future 是惰性的(创建后不自动执行),基于 poll 的拉取模型。JavaScript 的 Promise 是急切的(创建后立即开始执行),基于回调的推送模型。Rust 的方式给了编译器更多优化空间,Future 可以是零成本抽象。

适用场景 ​

  • 理解异步原理:掌握 async/await 的底层机制
  • 库开发:编写异步运行时或底层异步库
  • 自定义异步原语:超时、重试、竞争等组合器
  • 性能调优:需要精确控制 Future 状态机

注意事项 ​

  • Future::poll 通常由运行时调用,开发者用 .await 即可
  • poll 接收 Pin<&mut Self>,保证 Future 不被移动
  • 返回 Pending 时必须确保 Waker 会在未来某个时间被调用
  • async fn 会自动生成 Future 实现,比手动实现更安全
  • Future 是零成本抽象,不需要堆分配(除非用 Box<dyn Future>)
  • 不要在 poll 中做阻塞操作,会阻塞整个执行器线程

总结 ​

Future trait 是 Rust 异步编程的基础,它代表一个可能尚未完成的计算。核心方法 poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> 返回 Ready(T) 表示完成,Pending 表示未完成。async fn 由编译器自动转换为实现 Future 的状态机。Pin 保证 Future 不被移动(防止自引用失效),Waker(通过 Context)是通知运行时重新 poll 的机制。开发者通常用 async/await 语法而不是手动实现 Future,但理解 poll 模型有助于掌握异步编程的工作原理和调试异步代码。