# std::prelude

每個 Rust 程式自動匯入的一小組常用名稱，讓你不寫 `use` 就能用 `Vec`、`Option`、`String`。

## 這個模組做什麼

寫 Rust 時，你從來沒寫過 `use std::vec::Vec;` 或 `use std::option::Option;`，卻能直接用 `Vec::new()`、`Some(1)`。原因是編譯器會在每個模組開頭偷偷插入一行：

```rust
use std::prelude::rust_2024::*;
```

前奏（prelude）就像飯店房間裡的「基本備品」：牙刷、毛巾一開始就放好了，不用另外跟櫃台要。標準庫把「幾乎每個程式都會用到」的型別與特徵（trait）放進這份清單，其餘的（例如 `HashMap`）才需要你自己 `use`。

| 情境 | 需要 `use` 嗎 |
| --- | --- |
| `Vec`、`String`、`Box`、`Option`、`Result` | 不用，在 prelude 裡 |
| `Clone`、`Copy`、`Default`、`Iterator`、`From`／`Into` | 不用，在 prelude 裡 |
| `HashMap`、`Rc`、`fs::File`、`io::Write` | 要，自己 `use` |
| 巨集 `println!`、`vec!`、`format!` | 不用，標準庫巨集本來就全域可用 |

prelude 只放「名稱」，不會讓程式變大：沒用到的東西不會被編進執行檔。

## 匯入

prelude 不需要匯入，編譯器自動處理。若想明確寫出來（例如在 `#![no_implicit_prelude]` 的模組裡），完整路徑是：

```rust
use std::prelude::rust_2024::*;
```

各 edition 對應的模組：`std::prelude::v1`（2015／2018 共用的基礎）、`std::prelude::rust_2015`、`std::prelude::rust_2018`、`std::prelude::rust_2021`、`std::prelude::rust_2024`。

## 常用 API

### prelude 裡的型別：Vec、String、Box、Option、Result

這五個是最常用的型別，全部不用 `use`。`Some`／`None`、`Ok`／`Err` 這些列舉成員（variant）也一起匯入了，所以可以直接寫 `Some(3)` 而不是 `Option::Some(3)`。

完整路徑：

```rust
std::vec::Vec
std::string::String
std::boxed::Box
std::option::Option::{self, Some, None}
std::result::Result::{self, Ok, Err}
```

範例：
```rust
fn find_even(v: &Vec<i32>) -> Option<i32> {
    v.iter().copied().find(|x| x % 2 == 0)
}

fn parse(s: &str) -> Result<i32, String> {
    s.parse::<i32>().map_err(|e| e.to_string())
}

fn main() {
    let v: Vec<i32> = vec![1, 3, 4, 7];
    let name: String = String::from("rust");
    let boxed: Box<i32> = Box::new(42);
    println!("{:?}", find_even(&v));
    println!("{:?}", parse("12"));
    println!("{:?}", parse("x"));
    println!("{} {}", name, boxed);
}
```

輸出：
```text
Some(4)
Ok(12)
Err("invalid digit found in string")
rust 42
```

### prelude 裡的特徵：方法為什麼能直接呼叫

特徵的方法要能呼叫，該特徵必須「在作用域內」。prelude 匯入了一批常用特徵，所以 `.clone()`、`.into()`、`.to_string()`、`.iter().map()` 都能直接用。

主要成員（Rust 2024 prelude）：

| 類別 | 特徵 |
| --- | --- |
| 複製與預設 | `Clone`、`Copy`、`Default` |
| 比較 | `PartialEq`、`Eq`、`PartialOrd`、`Ord` |
| 轉換 | `From`、`Into`、`AsRef`、`AsMut`、`TryFrom`、`TryInto`、`FromIterator` |
| 迭代 | `Iterator`、`IntoIterator`、`DoubleEndedIterator`、`ExactSizeIterator`、`Extend` |
| 字串與記憶體 | `ToString`、`ToOwned`、`Drop` |
| 閉包與標記 | `Fn`、`FnMut`、`FnOnce`、`Send`、`Sync`、`Sized`、`Unpin` |
| 非同步 | `Future`、`IntoFuture` |

範例：
```rust
#[derive(Debug, Clone, Default, PartialEq)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let p = Point { x: 1, y: 2 };
    let q = p.clone();
    let origin = Point::default();
    let n: i64 = 7i32.into();
    let s = 3.5f64.to_string();
    let doubled: Vec<i32> = [1, 2, 3].iter().map(|x| x * 2).collect();
    println!("{:?} {:?} {}", q, origin, p == q);
    println!("{} {} {:?}", n, s, doubled);
}
```

輸出：
```text
Point { x: 1, y: 2 } Point { x: 0, y: 0 } true
7 3.5 [2, 4, 6]
```

### 不在 prelude 裡的東西要自己 use

`HashMap`、`Rc`、`io::Write` 等不在 prelude 裡，忘記 `use` 會得到 `cannot find type` 或「方法不存在」的錯誤。特別是特徵：`write!` 寫入 `String` 需要 `std::fmt::Write`，寫入檔案需要 `std::io::Write`，兩者都不在 prelude。

範例：
```rust
use std::collections::HashMap;
use std::fmt::Write;
use std::rc::Rc;

fn main() {
    let mut scores: HashMap<&str, i32> = HashMap::new();
    scores.insert("amy", 90);
    let shared = Rc::new(String::from("shared"));
    let other = Rc::clone(&shared);
    let mut out = String::new();
    write!(out, "amy={}", scores["amy"]).unwrap();
    println!("{} {} {}", out, other, Rc::strong_count(&shared));
}
```

輸出：
```text
amy=90 shared 2
```

### 各 edition 的差異：rust_2021 加入的 TryFrom 與 FromIterator

edition（版次）是 Rust 每隔幾年一次、可選擇升級的語言版本，在 `Cargo.toml` 的 `edition` 欄位或 `rustc --edition` 指定。每個 edition 有自己的 prelude：

| 模組 | 相較前一版新增 |
| --- | --- |
| `rust_2015`／`rust_2018` | 與 `v1` 相同 |
| `rust_2021` | `TryFrom`、`TryInto`、`FromIterator` |
| `rust_2024` | `Future`、`IntoFuture` |

所以在 2021 之後，`u8::try_from(300)` 不用 `use std::convert::TryFrom;`。

範例：
```rust
fn main() {
    let ok = u8::try_from(200i32);
    let too_big = u8::try_from(300i32);
    let small: Result<u8, _> = 100u32.try_into();
    let collected = String::from_iter(['h', 'i']);
    println!("{:?} {:?} {:?} {}", ok, too_big.is_err(), small, collected);
}
```

輸出：
```text
Ok(200) true Ok(100) hi
```

### rust_2024 加入的 Future 與 IntoFuture

Rust 2024 起 `Future` 也在 prelude 裡，寫手動實作 `Future` 的型別時，不必再 `use std::future::Future;`。下面的範例自己做一個極簡的執行器（executor）：用 `std::task::Waker::noop()`（Rust 1.85 起）建立什麼都不做的喚醒器，反覆輪詢直到完成。非同步的完整說明見 [std::future](/pkg-future)。

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

async fn add(a: i32, b: i32) -> i32 {
    a + b
}

fn block_on<F: Future>(f: F) -> F::Output {
    let mut f = pin!(f);
    let mut cx = Context::from_waker(Waker::noop());
    loop {
        if let Poll::Ready(v) = f.as_mut().poll(&mut cx) {
            return v;
        }
    }
}

fn main() {
    println!("{}", block_on(add(2, 3)));
}
```

輸出：
```text
5
```

### 名稱衝突：自己的定義會蓋過 prelude

prelude 的名稱優先順序最低。你在模組裡定義或 `use` 了同名的東西，就會用你的版本，不會報錯。這讓標準庫可以在新 edition 加名稱而不破壞舊程式，但也代表自訂一個叫 `Result` 的型別別名會影響整個模組。

注意：若要在遮蔽後仍使用標準版本，寫完整路徑，例如 `std::result::Result`。

範例：
```rust
type Result<T> = std::result::Result<T, String>;

fn half(n: i32) -> Result<i32> {
    if n % 2 == 0 { Ok(n / 2) } else { Err(format!("{} 是奇數", n)) }
}

fn main() {
    let a: std::result::Result<i32, ()> = Ok(1);
    println!("{:?} {:?} {:?}", half(8), half(5), a);
}
```

輸出：
```text
Ok(4) Err("5 是奇數") Ok(1)
```

## 重點整理

- 編譯器在每個模組自動加上 `use std::prelude::rust_20xx::*;`，所以 `Vec`、`String`、`Option`、`Result`、`Box` 不用匯入
- prelude 也匯入常用特徵（`Clone`、`Iterator`、`Into`...），它們的方法才能直接呼叫
- `HashMap`、`Rc`、`io::Write`、`fmt::Write` 不在 prelude，要自己 `use`
- Rust 2021 起加入 `TryFrom`／`TryInto`／`FromIterator`，Rust 2024 起加入 `Future`／`IntoFuture`
- 自己的同名定義會蓋過 prelude，需要時用完整路徑指回標準版本
