# Rust 1.56

Rust 1.56 發布於 2021-10-21，目前最新修補版為 `1.56.1`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.56 推出 2021 版次（edition）。版次是「自願選用」的語言變更機制：舊專案維持原本的版次照常編譯，新專案的 `Cargo.toml` 寫 `edition = "2021"` 才會套用新規則，不同版次的 crate 可以互相相依。這次的變更比 2018 小，主要是一些需要選用才不會破壞舊程式碼的改進，例如閉包只捕捉用到的欄位、陣列的 `into_iter()` 以值走訪。對新手來說，大多數 `cargo fix --edition` 就能自動遷移，詳見 [版次演進](/evolution-editions)；同一版也讓 `Cargo.toml` 可以宣告最低支援的 Rust 版本 `rust-version`。

### 2021 版次的主要變更

- 閉包只捕捉實際用到的欄位，而不是整個變數（disjoint capture），詳見 [閉包](/closures-basics)。
- 陣列的 `array.into_iter()` 改為以值走訪，不再解析成走訪參考，詳見 [陣列](/pkg-array)。
- `macro_rules!` 的 `:pat` 會匹配最上層的 `A | B`。
- Cargo 的特性解析器預設改用第 2 版，詳見 [Cargo](/modules-cargo)。
- prelude 新增 `TryInto`、`TryFrom` 與 `FromIterator`，不必再手動 `use`，詳見 [prelude](/pkg-prelude)。
- `panic!` 等巨集一律把第一個參數當格式字串，和 `println!` 一致，詳見 [panic](/errors-panic)。
- 保留 `ident#`、`ident"..."`、`ident'...'` 這類語法供未來使用。
- `bare_trait_objects`（省略 `dyn` 的特徵物件）與 `ellipsis_inclusive_range_patterns`（`...` 範圍模式）從警告升級為錯誤，詳見 [特徵物件](/traits-objects)。

### 語言變更

- `binding @ pattern` 的模式部分也可以再引入新的綁定，詳見 [模式](/control-patterns)。
- `const fn` 中可以存取聯合體（union）欄位。

### 標準庫重點

- 所有集合型別都能用 `From` 從陣列建立，映射型別接受 `[(K, V); N]`，例如 `BTreeMap::from([...])`，詳見 [集合](/pkg-collections)。
- `Vec`、`String`、`OsString`、`PathBuf`、`BinaryHeap`、`VecDeque`、`HashMap`、`HashSet` 新增 `shrink_to`，詳見 [Vec](/pkg-vec)。
- 新增 `BufWriter::into_parts`、`UnsafeCell::raw_get`、`std::os::unix::fs::chroot`；`UnwindSafe` 等三個特徵也能從 `core::panic` 取得。
- `mem::transmute` 與切片的 `first`、`last`、`split_first`、`split_last` 成為 `const fn`。
- 環境變數名稱含有 NUL 或 `=` 時，相關函式視為該變數不存在，不再 panic，詳見 [std::env](/pkg-env)。

### Cargo 與工具

- `[package]` 可以設定 `rust-version` 宣告最低支援的 Rust 版本，版本不符時 Cargo 會提早報錯。
- 升級到 LLVM 13；新增 `--force-warn`，主要供 `cargo fix` 使用。

### 相容性注意

- Windows 上的命令列參數解析改為符合 C／C++ 標準函式庫的新規則。
- `SEMICOLON_IN_EXPRESSIONS_FROM_MACROS` 預設為警告；跳過多行的跳脫換行也會產生警告。
- 在 glibc 2.24 以下，從 `Command::pre_exec` 呼叫 `std::process::id` 可能取得不同的值。

### 閉包的分離捕捉

2021 版次起，閉包只捕捉它真正使用的欄位。下面的 `add` 只可變借用 `p.score`，所以同時讀 `p.name` 沒問題；`p.name` 被移走後，只用到 `p.score` 的閉包也照樣能建立。

範例：

```rust
struct Player {
    name: String,
    score: u32,
}

fn main() {
    let mut p = Player { name: String::from("Ann"), score: 0 };
    let mut add = |n: u32| p.score += n;
    println!("player: {}", p.name);
    add(10);
    add(5);
    println!("score: {}", p.score);

    let name = p.name;
    let show = || println!("score again: {}", p.score);
    show();
    println!("{name}");
}
```

輸出：

```text
player: Ann
score: 15
score again: 15
Ann
```

同一段程式用 `rustc --edition 2018` 編譯會失敗，因為閉包捕捉的是整個 `p`：

```text
error[E0502]: cannot borrow `p.name` as immutable because it is also borrowed as mutable
error[E0382]: borrow of partially moved value: `p`
```

注意：分離捕捉可能改變欄位被丟棄（drop）的順序，所以 `cargo fix` 遷移時會在需要的閉包裡插入 `let _ = &p;`，維持舊版捕捉整個變數的行為。

### binding @ pattern 中的新綁定

`名稱 @ 模式` 會把整個值綁到名稱上，現在後面的模式也能同時取出欄位，一次就拿到整體與部分。

範例：

```rust
#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let p @ Point { x, y } = Point { x: 3, y: -4 };
    println!("{:?} x={x} y={y}", p);

    match (1, 9) {
        whole @ (first, 5..=10) => println!("{:?} first={first}", whole),
        _ => println!("other"),
    }
}
```

輸出：

```text
Point { x: 3, y: -4 } x=3 y=-4
(1, 9) first=1
```

### 從陣列建立集合

集合型別可以直接用 `From` 從陣列建立，`BTreeMap::from([(鍵, 值), ...])` 比先建空映射再逐一 `insert` 更簡潔。`shrink_to(n)` 則把多餘容量縮到至少 `n`。

範例：

```rust
use std::collections::{BTreeMap, BTreeSet, VecDeque};

fn main() {
    let prices = BTreeMap::from([("tea", 30), ("coffee", 50)]);
    println!("{:?}", prices);

    let tags = BTreeSet::from(["rust", "go", "rust"]);
    println!("{:?}", tags);

    let mut v: Vec<i32> = Vec::with_capacity(100);
    v.extend([1, 2, 3]);
    v.shrink_to(10);
    println!("{} {}", v.len(), v.capacity() >= 10);

    let q = VecDeque::from([1, 2, 3]);
    println!("{:?}", q);
}
```

輸出：

```text
{"coffee": 50, "tea": 30}
{"go", "rust"}
3 true
[1, 2, 3]
```

## 本版新增的棄用 API

本版沒有新增棄用 API。

## 修補版本

| 版本 | 發布日期 | 含安全修補 | 內容（官方原文） |
| --- | --- | --- | --- |
| `1.56.1` | 2021-11-01 | 是 | New lints to detect the presence of bidirectional-override Unicode codepoints in the compiled source code ([CVE-2021-42574]) |

## 已知漏洞

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

### 本版已修正

| 編號 | 元件 | 摘要（官方原文） | 影響範圍 | 修正於 |
| --- | --- | --- | --- | --- |
| [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) |

### 仍影響 `1.56.1`

| 編號 | 元件 | 摘要（官方原文） | 影響範圍 | 修正於 |
| --- | --- | --- | --- | --- |
| [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) |

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

## 資料來源

- [Rust 1.56 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1560-2021-10-21)
- [Rust 1.56 發布公告](https://blog.rust-lang.org/releases/1.56.0/)
- [rust-lang/rust 原始碼 1.56.0](https://github.com/rust-lang/rust/tree/1.56.0)
