# Rust 1.66

Rust 1.66 發布於 2022-12-15，目前最新修補版為 `1.66.1`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.66 讓帶欄位的列舉也能指定明確的判別值（discriminant），方便與 C 等其他語言交換資料。標準庫穩定了 `std::hint::black_box`，寫效能測試時可以阻止編譯器把要測的程式最佳化掉；Cargo 則新增 `cargo remove`，與 1.62 的 `cargo add` 成對。升級要注意：不透明型別（`impl Trait`）不再隱含生命週期約束，這是健全性修正，少數依賴舊行為的程式需要調整。

### 語言變更

- 所有 `repr(整數)` 列舉都能寫明確判別值，包含帶欄位的變體，列舉見 [列舉](/enums-basics)。
- 模式可以寫 `..=X` 表示「小於等於 X」，詳見 [match](/control-match)。
- 常數求值錯誤從預設拒絕的 lint 改成硬性錯誤。
- `for_loops_over_fallibles` lint 從 Clippy 移入 rustc，提醒對 `Option`、`Result` 寫 `for` 迴圈的疑似錯誤。
- inline assembly 的 `sym` 運算元穩定；Unicode 更新到 15 版。

### 標準庫重點

- `BTreeMap` 新增 `first_key_value`、`last_key_value`、`pop_first`、`pop_last` 等方法，`BTreeSet` 新增 `first`、`last`、`pop_first`、`pop_last`，詳見 [BTreeMap](/pkg-collections-btree-map)。
- 無號整數新增 `checked_add_signed` 等方法，有號整數新增 `checked_add_unsigned`、`checked_sub_unsigned` 等方法，詳見 [std::num](/pkg-num)。
- `Option::unzip` 把 `Option<(A, B)>` 拆成 `(Option<A>, Option<B>)`，詳見 [std::option](/pkg-option)。
- `core::hint::black_box` 穩定：把值原封不動傳回，但讓編譯器無法推測它會被怎麼使用。
- `Duration::try_from_secs_f32`／`try_from_secs_f64` 在輸入為負或過大時回傳錯誤而不 panic，詳見 [std::time](/pkg-time)。
- `std::os::fd` 模組穩定；`Box<[T; N]>` 實作 `TryFrom<Vec<T>>`。

### Cargo 與工具

- 新增 `cargo remove`，從 `Cargo.toml` 移除相依，詳見 [Cargo](/modules-cargo)。
- `cargo publish` 會等到新版本可以下載後才結束。
- rustdoc 對文件中無效的 HTML 標籤發出警告。

### 相容性注意

- 不透明型別不再隱含生命週期約束，依賴錯誤行為的程式可能編譯失敗。
- `std::process::Command` 產生的子行程預設繼承父行程的訊號遮罩（signal mask），詳見 [std::process](/pkg-process)。

### 帶欄位列舉的明確判別值

列舉加上 `#[repr(u8)]` 後，每個變體在記憶體中都以一個 `u8` 判別值開頭。以前只有「全部變體都沒有欄位」時能用 `= 值` 指定它；現在帶欄位的變體也可以。對沒有欄位的列舉可以用 `as` 取得判別值，帶欄位的則沒有語言層級的取法，要用 `unsafe` 讀出記憶體第一個位元組；`repr(u8)` 保證這個布局。unsafe 的使用原則見 [unsafe](/lowlevel-unsafe)。

範例：

```rust
#[repr(u8)]
enum Packet {
    Ping = 1,
    Data(u16) = 10,
    Close { code: u8 } = 255,
}

fn tag(p: &Packet) -> u8 {
    unsafe { *(p as *const Packet as *const u8) }
}

fn describe(p: &Packet) -> String {
    match p {
        Packet::Ping => "ping".to_string(),
        Packet::Data(len) => format!("data {len}"),
        Packet::Close { code } => format!("close {code}"),
    }
}

fn main() {
    for p in [Packet::Ping, Packet::Data(512), Packet::Close { code: 7 }] {
        println!("{} -> {}", tag(&p), describe(&p));
    }
}
```

輸出：

```text
1 -> ping
10 -> data 512
255 -> close 7
```

注意：這個功能主要用在跨語言 FFI；只是想比較「兩個值是不是同一個變體」時，改用安全的 `std::mem::discriminant`，見 [std::mem](/pkg-mem)。

### BTreeMap 取出最小與最大項目

`BTreeMap` 依鍵排序，現在可以直接拿到第一個（最小）與最後一個（最大）項目，`pop_first`／`pop_last` 則會一併移除。用它當簡易的優先佇列，依優先序處理工作。

範例：

```rust
use std::collections::BTreeMap;

fn main() {
    let mut tasks = BTreeMap::new();
    tasks.insert(3, "寫測試");
    tasks.insert(1, "修 bug");
    tasks.insert(2, "code review");

    println!("{:?} {:?}", tasks.first_key_value(), tasks.last_key_value());

    while let Some((prio, task)) = tasks.pop_first() {
        println!("處理 {prio}: {task}");
    }
    println!("{}", tasks.is_empty());
}
```

輸出：

```text
Some((1, "修 bug")) Some((3, "寫測試"))
處理 1: 修 bug
處理 2: code review
處理 3: 寫測試
true
```

### ..=X 範圍模式與帶號加法

`match` 的範圍模式現在可以省略起點，寫成 `..=-1` 表示「所有小於等於 -1 的值」。同一版的 `checked_add_signed` 讓無號整數加上一個有號整數，結果超出範圍就回傳 `None`；`Option::unzip` 則是 `Iterator::unzip` 之外，把一個 `Option` 裡的配對拆開的方法。

範例：

```rust
fn bucket(n: i32) -> &'static str {
    match n {
        ..=-1 => "負數",
        0 => "零",
        1..=9 => "個位數",
        _ => "兩位數以上",
    }
}

fn main() {
    for n in [-5, 0, 7, 42] {
        println!("{n}: {}", bucket(n));
    }
    let base: u32 = 10;
    println!("{:?} {:?}", base.checked_add_signed(-3), base.checked_add_signed(-11));
    let (pairs, flags): (Vec<i32>, Vec<bool>) = (1..=3).map(|x| (x * x, x % 2 == 0)).unzip();
    println!("{pairs:?} {flags:?}");
    println!("{:?}", Some((1, "a")).unzip());
}
```

輸出：

```text
-5: 負數
0: 零
7: 個位數
42: 兩位數以上
Some(7) None
[1, 4, 9] [false, true, false]
(Some(1), Some("a"))
```

## 本版新增的棄用 API

本版沒有新增棄用 API。

## 修補版本

| 版本 | 發布日期 | 含安全修補 | 內容（官方原文） |
| --- | --- | --- | --- |
| `1.66.1` | 2023-01-10 | 是 | Added validation of SSH host keys for git URLs in Cargo (CVE-2022-46176) |

## 已知漏洞

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

### 本版已修正

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

### 仍影響 `1.66.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) |

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

## 資料來源

- [Rust 1.66 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1660-2022-12-15)
- [Rust 1.66 發布公告](https://blog.rust-lang.org/releases/1.66.0/)
- [rust-lang/rust 原始碼 1.66.0](https://github.com/rust-lang/rust/tree/1.66.0)
