# Rust 1.95

Rust 1.95 發布於 2026-04-16，目前最新修補版為 `1.95.0`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.95 把 1.88 的 let chains 延伸到 `match`：比對分支的守衛（guard）可以寫 `if let`，在同一個分支裡繼續做模式比對。標準庫新增 `cfg_select!` 巨集，像編譯期的 `match` 一樣依平台或設定選擇程式碼，用途與熱門的第三方 crate `cfg-if` 相同。升級時要注意：`Eq::assert_receiver_is_total_eq` 被標記為棄用；JSON 目標規格改為需要 `-Z unstable-options` 才能使用；`#[non_exhaustive]` 列舉即使只有一個變體，比對時也會讀取判別值，可能改變閉包的捕獲行為。

### 語言變更

- 穩定 match 分支的 `if let` 守衛，詳見 [match 比對](/control-match)。
- `irrefutable_let_patterns` lint 不再對 let chains 發出警告。
- 支援以重新命名的方式匯入路徑關鍵字（如 `self`、`super`），詳見[模組系統](/modules-system)。
- 穩定 PowerPC 與 PowerPC64 的內嵌組合語言。
- 判斷運算式能否隱式提升為常數時，不再為此求值 const 區塊。

### 標準庫重點

- `cfg_select!` 巨集依 `cfg` 條件選擇第一個成立的分支，詳見[宣告式巨集](/macros-declarative)。
- `Vec::push_mut`、`Vec::insert_mut` 與 `VecDeque`、`LinkedList` 的 `push_*_mut` 系列：插入後回傳新元素的可變參考，詳見 [Vec](/pkg-vec)。
- 原子型別新增 `update`、`try_update`（`AtomicBool`、`AtomicPtr` 與各整數原子型別），詳見 [std::sync::atomic](/pkg-sync-atomic)。
- 新增 `mod core::range` 與 `core::range::RangeInclusive`，詳見 [std::ops](/pkg-ops)。
- `bool: TryFrom<{integer}>`、`core::hint::cold_path`、`Layout::repeat` 等 `Layout` 方法，以及 `MaybeUninit`、`Cell` 陣列的多個轉換實作。
- `fmt::from_fn`、`ControlFlow::is_break`、`is_continue` 可在 const 情境使用。

### Cargo 與工具

- 穩定 `--remap-path-scope`，控制產出檔案中路徑重新映射的範圍。
- rustdoc 搜尋結果把不穩定項目排在後面，並新增「隱藏棄用項目」設定。

### 相容性注意

- `Eq::assert_receiver_is_total_eq` 標記為棄用，手動實作會出現未來相容性警告，詳見[棄用 API](/deprecations)。
- `use $crate::{self};` 這類不重新命名的 `$crate` 匯入不再允許。
- 比對 `#[non_exhaustive]` 列舉時一律讀取判別值，閉包可能捕獲原本不會捕獲的值，詳見[閉包](/closures-basics)。
- 新增 `ambiguous_glob_imported_traits` 未來相容性 lint，針對歧義的 glob 匯入 trait。
- 陣列強制轉型產生的型別推斷限制可能變少；JSON 目標規格需要 `-Z unstable-options`。

### match 的 if let 守衛

[match](/control-match) 分支後面可以加 `if 條件` 當守衛；現在守衛也能寫 `if let`，並可以和 `&&` 串接其他條件，守衛中綁定的變數（如 `age`）可以在分支本體使用。守衛不成立時會繼續嘗試下一個分支。

範例：

```rust
fn parse_age(s: &str) -> Result<u32, std::num::ParseIntError> {
    s.trim().parse()
}

fn classify(input: Option<&str>) -> String {
    match input {
        Some(s) if let Ok(age) = parse_age(s) && age >= 18 => format!("成年：{age}"),
        Some(s) if let Ok(age) = parse_age(s) => format!("未成年：{age}"),
        Some(s) => format!("無法解析：{s:?}"),
        None => String::from("沒有資料"),
    }
}

fn main() {
    for input in [Some("20"), Some(" 9 "), Some("abc"), None] {
        println!("{}", classify(input));
    }
}
```

輸出：

```text
成年：20
未成年：9
無法解析："abc"
沒有資料
```

注意：和一般 `if` 守衛一樣，編譯器檢查 match 是否涵蓋所有情況時，不會把 `if let` 守衛裡的模式算進去，所以範例仍需要最後的 `Some(s)` 分支。

### cfg_select!

`cfg_select!` 依序檢查每個分支的 `cfg` 條件，展開第一個成立的分支，`_` 是全部不成立時的預設。它可以放在項目位置（選擇要定義哪個函式），也可以放在運算式位置（選擇一個值）。輸出取決於編譯的平台，以下是在 64 位元 macOS 上的結果。

範例：

```rust
cfg_select! {
    unix => {
        fn platform() -> &'static str { "類 Unix 系統" }
    }
    windows => {
        fn platform() -> &'static str { "Windows" }
    }
    _ => {
        fn platform() -> &'static str { "其他平台" }
    }
}

fn main() {
    let width = cfg_select! {
        target_pointer_width = "64" => "64 位元",
        _ => "非 64 位元",
    };
    println!("{}，{}", platform(), width);
}
```

輸出：

```text
類 Unix 系統，64 位元
```

### Vec::push_mut

以前 `push` 之後想修改剛放進去的元素，要再寫 `last_mut().unwrap()`。`push_mut` 直接回傳新元素的 `&mut T`；`insert_mut(i, 值)` 則是插入到索引 `i` 並回傳其可變參考。

範例：

```rust
fn main() {
    let mut names: Vec<String> = Vec::new();
    let first = names.push_mut(String::from("rust"));
    first.make_ascii_uppercase();
    println!("{names:?}");

    let middle = names.insert_mut(0, String::from("hello"));
    middle.push('!');
    println!("{names:?}");
}
```

輸出：

```text
["RUST"]
["hello!", "RUST"]
```

## 本版新增的棄用 API

本版沒有新增棄用 API。

## 修補版本

本版沒有修補版本。

## 已知漏洞

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

### 本版已修正

| 編號 | 元件 | 摘要（官方原文） | 影響範圍 | 修正於 |
| --- | --- | --- | --- | --- |
| [CVE-2026-40200](https://www.cve.org/CVERecord?id=CVE-2026-40200) | vendored | Apply patches for CVE-2026-6042 and CVE-2026-40200 to vendored musl | 未公布 | [1.95.0](/rust-1-95) |
| [CVE-2026-6042](https://www.cve.org/CVERecord?id=CVE-2026-6042) | vendored | Apply patches for CVE-2026-6042 and CVE-2026-40200 to vendored musl | 未公布 | [1.95.0](/rust-1-95) |

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

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

## 資料來源

- [Rust 1.95 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1950-2026-04-16)
- [Rust 1.95 發布公告](https://blog.rust-lang.org/releases/1.95.0/)
- [rust-lang/rust 原始碼 1.95.0](https://github.com/rust-lang/rust/tree/1.95.0)
