# std::future

定義「未來才會完成的值」：`Future` 特徵（trait），也是 `async`／`.await` 的基礎。

## 這個模組做什麼

Future 代表一個「還沒算完的工作」，例如等網路回應、等計時器。和執行緒不同，Future 本身不會自己跑：要有人反覆呼叫它的 `poll` 方法問「好了沒？」，它回答 `Poll::Ready(值)` 或 `Poll::Pending`。負責呼叫 `poll` 的程式叫做執行器（executor）。

| 名稱 | 用途 |
| --- | --- |
| `Future` 特徵 | 定義 `poll`，所有非同步工作的共同介面 |
| `async fn`、`async { }` | 編譯器自動產生 Future 的語法 |
| `.await` | 在 async 裡等待另一個 Future 完成 |
| `ready(v)` | 立刻完成的 Future |
| `pending()` | 永遠不會完成的 Future |
| `poll_fn(f)` | 用閉包臨時做出一個 Future |
| `IntoFuture` | 可以被 `.await` 的型別 |

標準庫**沒有**內建執行器。實務上會用第三方執行環境，本頁只用標準庫，自己寫一個最小的 `block_on` 來執行範例。`poll` 用到的 `Context`、`Waker`、`Poll` 定義在 [std::task](/pkg-task)；`poll` 的 `self` 必須是 `Pin<&mut Self>`，原因見 [std::pin](/pkg-pin)。

## 匯入

```rust
use std::future::{Future, ready, pending, poll_fn};
use std::task::{Context, Poll};
```

`Future` 與 `IntoFuture` 從 Rust 2024 版次起已在 prelude 中（`std::future::Future`），寫 `use` 也不會出錯。

## 常用 API

### Future 特徵：poll 與 Poll

`Future` 只有一個必要方法 `poll`，以及關聯型別 `Output`（完成後產生的值）。下面手動實作一個「需要被問兩次才完成」的 Future，並用 `Waker::noop()`（Rust 1.85 起，一個什麼都不做的喚醒器）親自呼叫 `poll`，看看執行器實際在做什麼。

簽名：
```rust
pub trait Future {
    type Output;
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>;
}
```

範例：
```rust
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll, Waker};

struct Download {
    progress: u32,
}

impl Future for Download {
    type Output = &'static str;
    fn poll(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.progress += 50;
        if self.progress >= 100 {
            Poll::Ready("下載完成")
        } else {
            Poll::Pending
        }
    }
}

fn main() {
    let mut fut = Download { progress: 0 };
    let mut cx = Context::from_waker(Waker::noop());
    for round in 1..=3 {
        let r = Pin::new(&mut fut).poll(&mut cx);
        println!("第 {round} 次 poll：{:?}", r);
        if r.is_ready() {
            break;
        }
    }
}
```

輸出：
```text
第 1 次 poll：Pending
第 2 次 poll：Ready("下載完成")
```

注意：一個 Future 回傳 `Ready` 之後就不應再被 poll；再 poll 的行為由實作決定，`async` 產生的 Future 會 panic。

### 自己寫最小執行器：block_on

執行器的工作：反覆 poll Future，回傳 `Pending` 時先休息，等 Future 透過 `Waker` 通知「可以再問了」才繼續。最小版本用目前執行緒當工作者：休息用 `thread::park()`，喚醒用 `unpark()`。`Wake` 特徵讓一個用 `Arc` 包起來的結構直接變成 `Waker`，細節見 [std::task](/pkg-task)。

簽名：
```rust
fn block_on<F: Future>(fut: F) -> F::Output
```

範例：
```rust
use std::future::Future;
use std::pin::pin;
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};
use std::thread::{self, Thread};

struct ThreadWaker(Thread);

impl Wake for ThreadWaker {
    fn wake(self: Arc<Self>) {
        self.0.unpark();
    }
}

fn block_on<F: Future>(fut: F) -> F::Output {
    let mut fut = pin!(fut);
    let waker = Waker::from(Arc::new(ThreadWaker(thread::current())));
    let mut cx = Context::from_waker(&waker);
    loop {
        match fut.as_mut().poll(&mut cx) {
            Poll::Ready(v) => return v,
            Poll::Pending => thread::park(),
        }
    }
}

fn main() {
    let answer = block_on(async { 6 * 7 });
    println!("答案是 {answer}");
}
```

輸出：
```text
答案是 42
```

`thread::park` 可能無故醒來，但這沒關係：醒來後只是多 poll 一次，Future 沒好就再回傳 `Pending`。之後的範例都會沿用這個 `block_on`。

### async fn 與 async 區塊：自動產生 Future

`async fn` 呼叫後**不會**馬上執行函式本體，而是回傳一個 Future；`async { }` 區塊也一樣。只有被 poll（例如交給 `block_on` 或被 `.await`）時才開始跑。這叫做惰性（lazy）。

簽名：
```rust
async fn name(args) -> T
fn name(args) -> impl Future<Output = T>
```

範例：
```rust
use std::future::Future;
use std::pin::pin;
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};
use std::thread::{self, Thread};

struct ThreadWaker(Thread);
impl Wake for ThreadWaker {
    fn wake(self: Arc<Self>) {
        self.0.unpark();
    }
}
fn block_on<F: Future>(fut: F) -> F::Output {
    let mut fut = pin!(fut);
    let waker = Waker::from(Arc::new(ThreadWaker(thread::current())));
    let mut cx = Context::from_waker(&waker);
    loop {
        match fut.as_mut().poll(&mut cx) {
            Poll::Ready(v) => return v,
            Poll::Pending => thread::park(),
        }
    }
}

async fn add(a: i32, b: i32) -> i32 {
    println!("  add 開始執行");
    a + b
}

fn main() {
    let fut = add(2, 3);
    println!("已呼叫 add，但還沒執行");
    let block = async {
        println!("  區塊開始執行");
        "區塊結果"
    };
    println!("結果：{}", block_on(fut));
    println!("結果：{}", block_on(block));
}
```

輸出：
```text
已呼叫 add，但還沒執行
  add 開始執行
結果：5
  區塊開始執行
結果：區塊結果
```

### .await：串接多個 Future

在 `async` 函式或區塊裡，`expr.await` 會等 `expr` 這個 Future 完成並取得結果。如果它還沒好，整個外層 Future 也回傳 `Pending`，下次被 poll 時從同一個位置繼續。這讓非同步程式寫起來像一般的循序程式。

注意：`.await` 只能用在 `async` 的上下文中；在一般 `fn main` 裡要交給執行器。

簽名：
```rust
future.await
```

範例：
```rust
use std::future::Future;
use std::pin::pin;
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};
use std::thread::{self, Thread};

struct ThreadWaker(Thread);
impl Wake for ThreadWaker {
    fn wake(self: Arc<Self>) {
        self.0.unpark();
    }
}
fn block_on<F: Future>(fut: F) -> F::Output {
    let mut fut = pin!(fut);
    let waker = Waker::from(Arc::new(ThreadWaker(thread::current())));
    let mut cx = Context::from_waker(&waker);
    loop {
        match fut.as_mut().poll(&mut cx) {
            Poll::Ready(v) => return v,
            Poll::Pending => thread::park(),
        }
    }
}

async fn fetch_price(item: &str) -> u32 {
    match item {
        "咖啡" => 60,
        "蛋糕" => 85,
        _ => 0,
    }
}

async fn order(items: &[&str]) -> u32 {
    let mut total = 0;
    for item in items {
        let p = fetch_price(item).await;
        println!("{item}：{p}");
        total += p;
    }
    total
}

fn main() {
    let total = block_on(order(&["咖啡", "蛋糕"]));
    println!("合計 {total}");
}
```

輸出：
```text
咖啡：60
蛋糕：85
合計 145
```

### ready 與 pending：現成的 Future

`ready(v)` 第一次被 poll 就回傳 `Ready(v)`，適合在需要 Future 的地方直接給值。`pending()` 永遠回傳 `Pending`，常用於測試或表示「永遠不會發生的事件」。

簽名：
```rust
pub fn ready<T>(t: T) -> Ready<T>
pub fn pending<T>() -> Pending<T>
```

範例：
```rust
use std::future::{Future, pending, ready};
use std::pin::pin;
use std::task::{Context, Waker};

fn main() {
    let mut cx = Context::from_waker(Waker::noop());

    let mut a = pin!(ready("快取命中"));
    println!("{:?}", a.as_mut().poll(&mut cx));

    let mut b = pin!(pending::<i32>());
    println!("{:?}", b.as_mut().poll(&mut cx));
    println!("{:?}", b.as_mut().poll(&mut cx));
}
```

輸出：
```text
Ready("快取命中")
Pending
Pending
```

### poll_fn：用閉包做 Future

`poll_fn`（Rust 1.64 起）把一個「接收 `&mut Context`、回傳 `Poll`」的閉包包成 Future，不必另外定義結構。下面做出一個第三次 poll 才完成的 Future；每次回傳 `Pending` 前都呼叫 `wake_by_ref()`，請執行器馬上再 poll 一次。

注意：回傳 `Pending` 卻從不安排喚醒，搭配會 `park` 的執行器就會永遠卡住。

簽名：
```rust
pub fn poll_fn<T, F>(f: F) -> PollFn<F>
where F: FnMut(&mut Context<'_>) -> Poll<T>
```

範例：
```rust
use std::future::{Future, poll_fn};
use std::pin::pin;
use std::sync::Arc;
use std::task::{Context, Poll, Wake, Waker};
use std::thread::{self, Thread};

struct ThreadWaker(Thread);
impl Wake for ThreadWaker {
    fn wake(self: Arc<Self>) {
        self.0.unpark();
    }
}
fn block_on<F: Future>(fut: F) -> F::Output {
    let mut fut = pin!(fut);
    let waker = Waker::from(Arc::new(ThreadWaker(thread::current())));
    let mut cx = Context::from_waker(&waker);
    loop {
        match fut.as_mut().poll(&mut cx) {
            Poll::Ready(v) => return v,
            Poll::Pending => thread::park(),
        }
    }
}

fn main() {
    let mut tries = 0;
    let fut = poll_fn(|cx| {
        tries += 1;
        println!("第 {tries} 次被 poll");
        if tries < 3 {
            cx.waker().wake_by_ref();
            Poll::Pending
        } else {
            Poll::Ready(tries * 100)
        }
    });
    println!("結果 {}", block_on(fut));
}
```

輸出：
```text
第 1 次被 poll
第 2 次被 poll
第 3 次被 poll
結果 300
```

### IntoFuture：讓自訂型別可以 .await

`.await` 實際上會先呼叫 `IntoFuture::into_future`。所有 `Future` 自動實作 `IntoFuture`；你也可以替「設定好參數的請求建構器」之類的型別實作它，讓使用者直接 `.await` 而不必多呼叫一個 `send()`。

簽名：
```rust
pub trait IntoFuture {
    type Output;
    type IntoFuture: Future<Output = Self::Output>;
    fn into_future(self) -> Self::IntoFuture;
}
```

範例：
```rust
use std::future::{Future, IntoFuture, Ready, ready};
use std::pin::pin;
use std::task::{Context, Poll, Waker};

struct Query {
    table: &'static str,
    limit: usize,
}

impl IntoFuture for Query {
    type Output = String;
    type IntoFuture = Ready<String>;
    fn into_future(self) -> Ready<String> {
        ready(format!("SELECT * FROM {} LIMIT {}", self.table, self.limit))
    }
}

fn main() {
    let task = async { Query { table: "users", limit: 5 }.await };
    let mut task = pin!(task);
    let mut cx = Context::from_waker(Waker::noop());
    if let Poll::Ready(sql) = task.as_mut().poll(&mut cx) {
        println!("{sql}");
    }
}
```

輸出：
```text
SELECT * FROM users LIMIT 5
```

## 重點整理

- Future 是「被 poll 才會前進」的工作，`poll` 回傳 `Poll::Ready(值)` 或 `Poll::Pending`
- `async fn` 與 `async { }` 是惰性的：呼叫只產生 Future，交給執行器或 `.await` 才執行
- 標準庫不含執行器；最小的 `block_on` 用 `pin!`、`Wake`、`thread::park` 就能寫出來
- 回傳 `Pending` 時必須安排日後呼叫 `Waker`，否則執行器不會再 poll
- `ready`、`pending`、`poll_fn` 可快速做出 Future；實作 `IntoFuture` 讓自訂型別支援 `.await`
