# Rust 1.21

Rust 1.21 發布於 2017-10-12，目前最新修補版為 `1.21.0`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.21 是一個小而實用的版本：對常數字面值取參考（如 `&5`）會自動提升成 `'static`，可以直接傳給 `thread::spawn` 這類要求 `'static` 的函式。標準庫穩定了 `Iterator::for_each`、`Ord::max`／`min` 與 `mem::discriminant`，所有元素可 `Clone` 的陣列與元組都自動實作 `Clone`。Cargo 新增 `[patch]` 區段，可以暫時用本機或其他來源的版本取代相依樹中的某個 crate。

### 語言變更

- 可以放進 `static` 的常數運算式，取參考後會提升為 `&'static`，例如 `let x: &'static u32 = &0;`，詳見 [生命週期](/ownership-lifetimes)。
- 路徑語法放寬，任何位置都可以在 `<` 前寫 `::`，例如巨集參數裡的 `Vec::<i32>::new`。

### 標準庫重點

- 新增 `Iterator::for_each`，在迭代器鏈的最後對每個元素執行動作，詳見 [迭代器](/iterators-basics)。
- `Ord` 特徵的 `max`、`min` 方法穩定，詳見 [std::cmp](/pkg-cmp)。
- 新增 `mem::discriminant`，不用 `match` 就能比較兩個列舉值是不是同一個變體；`mem::needs_drop` 也穩定，詳見 [std::mem](/pkg-mem)。
- 所有元素為 `T: Clone` 的陣列與元組都實作 `Clone`，不再受長度 32 的限制，詳見 [陣列](/pkg-array)。
- `Rc` 與 `Arc` 實作 `From<&[T]>`、`From<str>`、`From<String>`、`From<Box<T>>`、`From<Vec<T>>`，詳見 [std::rc](/pkg-rc)。
- `Stdin`、`Stdout`、`Stderr` 實作 `AsRawFd`。

### Cargo 與工具

- `Cargo.toml` 新增 `[patch]` 區段，取代相依樹中的某個 crate，建議用來取代舊的 `[replace]`，詳見 [Cargo.toml](/modules-cargo)。
- `cargo install` 可以一次安裝多個套件；在虛擬工作區中執行指令會自動帶 `--all`，詳見 [工作區](/modules-workspaces)。
- 新增 `--all-targets`；`include`、`exclude` 欄位接受類似 `.gitignore` 的樣式。
- 把必要相依當作 feature 使用已被棄用，會產生警告。
- 可以用 `rustup component add rls-preview` 安裝 RLS 預覽版；新增 rustdoc 文件（The rustdoc Book），Cargo 文件改放在 doc.rust-lang.org/cargo。

### 相容性注意

- 對高階型別（higher-ranked type）的方法比對規則改變，少數子型別邊角情況可能無法編譯。
- `rustc` JSON 錯誤輸出的位元組位置改為從檔案開頭起算。
- `unused_results` lint 不再忽略布林值。

### 常數字面值提升為 'static

`thread::spawn` 要求閉包捕獲的資料活得夠久，也就是 `'static`。以前 `let limit = &100;` 是指向區域暫存值的參考，傳進新執行緒會出現「borrowed value does not live long enough」。現在只要被參考的值能放進 `static`，編譯器就會把它當成靜態資料，參考自然是 `&'static`，詳見 [執行緒](/concurrency-threads)。

範例：

```rust
use std::thread;

fn main() {
    let limit = &100;
    let handle = thread::spawn(move || {
        println!("子執行緒看到的上限：{}", limit);
    });
    handle.join().unwrap();

    let defaults: &'static [i32] = &[1, 2, 3];
    println!("{:?}", defaults);
}
```

輸出：

```text
子執行緒看到的上限：100
[1, 2, 3]
```

注意：只有常數運算式會被提升；`&String::from("x")` 或 `&some_variable` 仍是區域參考，不會變成 `'static`。

### Iterator::for_each

`for_each` 會把迭代器消耗完，對每個元素呼叫閉包，效果和 `for` 迴圈相同。一長串 `map`、`filter` 接在一起時，用 `for_each` 收尾可以維持從左到右的閱讀順序；單純的迴圈則用 `for` 通常更清楚。

範例：

```rust
fn main() {
    (1..=5)
        .map(|x| x * x)
        .filter(|x| x % 2 == 1)
        .for_each(|x| println!("奇數平方：{}", x));

    let mut total = 0;
    [10, 20, 30].iter().for_each(|n| total += n);
    println!("總和：{}", total);

    println!("{} {}", 3.max(9), "apple".min("banana"));
}
```

輸出：

```text
奇數平方：1
奇數平方：9
奇數平方：25
總和：60
9 apple
```

注意：`for_each` 的閉包裡不能用 `break` 或 `continue` 提早結束；需要中途停止時改用 `for` 迴圈，或用 Rust 1.27 起提供的 `try_for_each`。

## 本版新增的棄用 API

本版沒有新增棄用 API。

## 修補版本

本版沒有修補版本。

## 已知漏洞

影響 `1.21.0` 的已知漏洞共 21 個；在本版修正的共 0 個；仍影響最新修補版 `1.21.0` 的共 21 個。官方未公布影響範圍的漏洞只列在修正它的版本，不計入其他版本。

### 仍影響 `1.21.0`

| 編號 | 元件 | 摘要（官方原文） | 影響範圍 | 修正於 |
| --- | --- | --- | --- | --- |
| [CVE-2026-5222](https://github.com/rust-lang/cargo/security/advisories/GHSA-p688-r7jv-fm6f) | cargo | Cargo can be coerced to share credentials between registries | 早於 1.96.0 | [1.96.0](/rust-1-96) |
| [CVE-2026-5223](https://github.com/rust-lang/cargo/security/advisories/GHSA-jq42-7mfv-hm57) | cargo | Crates in third party registries can override the cached source of other crates | 早於 1.96.0 | [1.96.0](/rust-1-96) |
| [CVE-2024-43402](https://github.com/rust-lang/rust/security/advisories/GHSA-2xg3-7mm6-98jj) | std | `std::process::Command` batch files argument escaping could be bypassed with trailing whitespace or periods | 早於 1.81.0 | [1.81.0](/rust-1-81) |
| [CVE-2024-24576](https://github.com/rust-lang/rust/security/advisories/GHSA-q455-m56c-85mh) | std | `std::process::Command` did not properly escape arguments of batch files on Windows | 早於 1.77.2 | [1.77.2](/rust-1-77) |
| [CVE-2023-38497](https://github.com/rust-lang/cargo/security/advisories/GHSA-j3xp-wfr4-hx87) | cargo | Cargo not respecting umask when extracting crate archives | 早於 1.71.1 | [1.71.1](/rust-1-71) |
| [CVE-2022-46176](https://github.com/rust-lang/cargo/security/advisories/GHSA-r5w3-xm58-jv6j) | cargo | Cargo did not verify SSH host keys | 早於 1.66.1 | [1.66.1](/rust-1-66) |
| [CVE-2022-36113](https://github.com/rust-lang/cargo/security/advisories/GHSA-rfj2-q3h3-hm5j) | cargo | Extracting malicious crates can corrupt arbitrary files | 早於 1.64.0 | [1.64.0](/rust-1-64) |
| [CVE-2022-36114](https://github.com/rust-lang/cargo/security/advisories/GHSA-2hvr-h6gw-qrxp) | cargo | Extracting malicious crates can fill the file system | 早於 1.64.0 | [1.64.0](/rust-1-64) |
| [CVE-2022-21658](https://github.com/rust-lang/rust/security/advisories/GHSA-r9cc-f5pr-p3j2) | std | Race condition in std::fs::remove_dir_all | 早於 1.58.1 | [1.58.1](/rust-1-58) |
| [CVE-2021-42574](https://github.com/rust-lang/rust/security/advisories/GHSA-rcv6-wg5m-24v6) | rustc | rustc and bidirectional-override codepoints in source code | 早於 1.56.1 | [1.56.1](/rust-1-56) |
| [CVE-2021-28878](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-28878) | std | Zip may call __iterator_get_unchecked twice with the same index | 1.14.0 起，早於 1.52.0 | [1.52.0](/rust-1-52) |
| [CVE-2021-28879](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-28879) | std | Zip can cause buffer overflow when a consumed Zip iterator is used again | 1.14.0 起，早於 1.52.0 | [1.52.0](/rust-1-52) |
| [CVE-2021-28876](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-28876) | std | Panic safety issue in Zip specialization | 1.14.0 起，早於 1.52.0 | [1.52.0](/rust-1-52) |
| [CVE-2021-28875](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-28875) | std | Logic bug in Read can cause buffer overflow in read_to_end() | 1.20.0 起，早於 1.50.0 | [1.50.0](/rust-1-50) |
| [CVE-2021-28877](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-28877) | std | TrustedRandomAccess specialization composes incorrectly for nested iter::Zips | 1.11.0 起，早於 1.51.0 | [1.51.0](/rust-1-51) |
| [CVE-2021-29922](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-29922) | std | Improper Input Validation of octal literals in `std::net` | 早於 1.53.0 | [1.53.0](/rust-1-53) |
| [CVE-2019-16760](https://github.com/rust-lang/rust/security/advisories/GHSA-phjm-8x66-qw4r) | cargo | Cargo prior to Rust 1.26.0 may download the wrong dependency | 早於 1.26.0 | [1.26.0](/rust-1-26) |
| [CVE-2019-1010299](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-1010299) | std | vec_deque::Iter has unsound Debug implementation | 1.18.0 起，早於 1.30.0 | [1.30.0](/rust-1-30) |
| [CVE-2018-1000657](https://github.com/rust-lang/rust/issues/44800) | std | Buffer overflow vulnerability in VecDeque::reserve() | 1.3.0 起，早於 1.22.0 | [1.22.0](/rust-1-22) |
| [CVE-2018-1000622](https://groups.google.com/forum/#!topic/rustlang-security-announcements/4ybxYLTtXuM) | rustdoc | Uncontrolled search path element vulnerability in rustdoc plugins | 早於 1.27.1 | [1.27.1](/rust-1-27) |
| [CVE-2018-25008](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-25008) | std | Insufficient synchronization in `Arc::get_mut` | 1.3.0 起，早於 1.29.0 | [1.29.0](/rust-1-29) |

本版已停止支援，不會再修正這些漏洞；請升級到 `1.100.1`。

## 資料來源

- [Rust 1.21 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1210-2017-10-12)
- [Rust 1.21 發布公告](https://blog.rust-lang.org/releases/1.21.0/)
- [rust-lang/rust 原始碼 1.21.0](https://github.com/rust-lang/rust/tree/1.21.0)
