# Rust 1.62

Rust 1.62 發布於 2022-06-30，目前最新修補版為 `1.62.1`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.62 帶來兩個日常就會用到的改進：`cargo add` 讓你在命令列直接加相依，`#[derive(Default)]` 也能用在列舉（enum）上，只要用 `#[default]` 標出預設變體。Linux 上的 `Mutex`、`Condvar`、`RwLock` 改用 futex 實作，更輕更快。升級要注意：`unaligned_references` lint 改為預設拒絕（deny），對 packed 結構欄位取參考的程式會編譯失敗。

### 語言變更

- `#[derive(Default)]` 支援列舉，以 `#[default]` 指定預設變體（只能標在沒有欄位的變體上），列舉見 [列舉](/enums-basics)。
- 解構指定（destructuring assignment）支援單元結構與單元列舉變體。
- `const fn` 可以宣告 `extern "C"` 或 `extern "Rust"`。

### 標準庫重點

- `bool::then_some` 在條件為真時回傳 `Some(值)`，否則 `None`，詳見 [布林與字元](/types-bool-char)。
- `f32::total_cmp`、`f64::total_cmp` 提供浮點數的全序比較，可直接拿來排序，詳見 [f64](/pkg-f64)。
- `Stdin::lines` 直接從標準輸入逐行讀取，詳見 [std::io](/pkg-io)。
- Linux 上的 `Mutex`、`Condvar`、`RwLock` 改用 futex 實作；`Mutex` 內部狀態只需 5 位元組，也不用額外配置記憶體，共享狀態見 [共享狀態](/concurrency-shared-state)。
- `Rc<str>` 可轉成 `Rc<[u8]>`，`Arc<str>` 可轉成 `Arc<[u8]>`。

### Cargo 與工具

- 新增 `cargo add`，可指定版本與 features，例如 `cargo add serde --features derive`、`cargo add nom@5`，詳見 [Cargo](/modules-cargo)。
- 套件 ID 支援 `name@version` 寫法，`cargo install`、`cargo yank` 也能用。
- `x86_64-unknown-none` 升為 Tier 2，可用 `rustup target add` 安裝，方便撰寫沒有作業系統的程式。
- 新增 lint 警告未使用的巨集規則（macro rule），巨集見 [宣告式巨集](/macros-declarative)。

### 相容性注意

- `unaligned_references` 改為預設拒絕，未來會成為硬性錯誤。
- rustdoc 會執行未匯出的 `macro_rules!` 巨集上的文件測試，文件測試見 [文件測試](/testing-doc)。
- `cargo test` 在指定目標等於主機目標時，也會把 `--target` 傳給 rustdoc。

### 列舉的 #[default]

結構體 derive `Default` 時，每個欄位都要有預設值；欄位是列舉時，以前得手寫 `impl Default`。現在在列舉上 derive `Default`，再用 `#[default]` 標出預設變體即可。

範例：

```rust
#[derive(Debug, Default)]
enum Level {
    Low,
    #[default]
    Medium,
    High,
}

#[derive(Debug, Default)]
struct Config {
    name: String,
    level: Level,
}

fn main() {
    let c = Config::default();
    println!("{c:?}");
    println!("{:?} {:?}", c.name, c.level);
    println!("{:?} {:?}", Level::Low, Level::High);
}
```

輸出：

```text
Config { name: "", level: Medium }
"" Medium
Low High
```

注意：`#[default]` 只能標在沒有欄位的變體；標在 `Some(T)` 這種帶資料的變體上會編譯失敗。

### bool::then_some：條件成立才給值

`cond.then_some(v)` 等於 `if cond { Some(v) } else { None }`。搭配 `filter_map` 可以把「篩選」與「轉換」寫成一步，`Option` 的用法見 [std::option](/pkg-option)。

範例：

```rust
fn main() {
    let n = 7;
    let even: Option<i32> = (n % 2 == 0).then_some(n);
    let odd: Option<i32> = (n % 2 == 1).then_some(n);
    println!("{even:?} {odd:?}");

    let nums = [1, 2, 3, 4, 5, 6];
    let picked: Vec<i32> = nums.iter().filter_map(|&x| (x > 3).then_some(x * 10)).collect();
    println!("{picked:?}");
}
```

輸出：

```text
None Some(7)
[40, 50, 60]
```

注意：`then_some` 的參數一定會先被求值；值的計算成本高時改用 `then(|| ...)`，只有條件成立才執行閉包。

### total_cmp：讓浮點數可以排序

`f64` 只實作 `PartialOrd`，因為 `NaN` 跟誰都無法比較，所以 `Vec<f64>` 不能直接 `sort()`。`total_cmp` 定義了一個全序：負無限大 < 負數 < `-0.0` < `0.0` < 正數 < 正無限大 < `NaN`（正號的 NaN），用在 `sort_by` 就不會 panic，也不需要 `unwrap`。

範例：

```rust
fn main() {
    let nan: f64 = "NaN".parse().unwrap();
    let mut values = vec![3.5, -0.0, nan, 1.0, 0.0, -2.25, f64::INFINITY];
    values.sort_by(|a, b| a.total_cmp(b));
    println!("{values:?}");
}
```

輸出：

```text
[-2.25, -0.0, 0.0, 1.0, 3.5, inf, NaN]
```

## 本版新增的棄用 API

本版沒有新增棄用 API。

## 修補版本

| 版本 | 發布日期 | 含安全修補 | 內容（官方原文） |
| --- | --- | --- | --- |
| `1.62.1` | 2022-07-19 | 否 | The compiler fixed unsound function coercions involving `impl Trait` return types.；The compiler fixed an incremental compilation bug with `async fn` lifetimes.；Windows added a fallback for overlapped I/O in synchronous reads and writes.；The `x86_64-fortanix-unknown-sgx` target added a mitigation for the MMIO stale data vulnerability, advisory [INTEL-SA-00615]. |

## 已知漏洞

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

### 仍影響 `1.62.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-40030](https://github.com/rust-lang/cargo/security/advisories/GHSA-wrrj-h57r-vx9p) | cargo | Malicious dependencies can inject arbitrary JavaScript into cargo-generated timing reports | 1.60.0 起，早於 1.72.0 | [1.72.0](/rust-1-72) |
| [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) |

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

## 資料來源

- [Rust 1.62 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1620-2022-06-30)
- [Rust 1.62 發布公告](https://blog.rust-lang.org/releases/1.62.0/)
- [rust-lang/rust 原始碼 1.62.0](https://github.com/rust-lang/rust/tree/1.62.0)
