# Rust 1.72

Rust 1.72 發布於 2023-08-24，目前最新修補版為 `1.72.1`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.72 讓編譯錯誤更好懂：找不到的項目若是被 `cfg` 關掉的（例如需要啟用某個 crate feature），編譯器會指出它在哪裡、被哪個條件關閉。常數求值也不再有步數上限，改為長時間執行時定期提示。另外有四個 Clippy lint 移入編譯器，例如 `invalid_nan_comparisons` 會警告 `x == f64::NAN` 這種永遠為假的比較。升級要注意：`Ipv6Addr` 對 IPv4 相容位址的 `Display` 輸出改變，Cargo 對 feature 名稱的字元檢查從警告變成錯誤。

### 語言變更

- 常數求值的步數上限改成 `const_eval_long_running` lint（預設拒絕），長時間求值會以倍增的間隔印出提示，常數見 [常數](/basics-constants)。
- 新增 rustc lint：`undropped_manually_drops`（拒絕）、`invalid_from_utf8_unchecked`（拒絕）、`invalid_from_utf8`（警告）、`invalid_nan_comparisons`（警告）、`invalid_reference_casting`（允許，預計 1.73 改為拒絕）。
- `dyn Trait` 不再要求指定帶 `Self: Sized` 約束的關聯型別，特徵物件見 [特徵物件](/traits-objects)。
- LoongArch64 的 inline asm 穩定。

### 標準庫重點

- `String::leak` 把 `String` 變成 `&'static mut str`，詳見 [String](/pkg-string)。
- `mpsc::Sender<T>` 在 `T: Send` 時實作 `Sync`，可以用共享參考在多個執行緒之間使用，詳見 [Send 與 Sync](/concurrency-send-sync)。
- `&OsStr` 可用 `TryFrom` 轉成 `&str`，詳見 [std::ffi](/pkg-ffi)。
- `CStr::from_bytes_with_nul`、`CStr::to_bytes`、`CStr::to_str` 可在 const 環境使用。
- `TypeId` 的雜湊改用 128 位元；`Arc`、`Rc`、`Weak` 的 `ptr_eq` 忽略指標的中繼資料。

### Cargo 與工具

- 被 `cfg` 停用的項目會出現在「找不到項目」的錯誤訊息中，並註明需要的 feature。
- 文件測試的工作目錄改為該測試所屬套件的根目錄，見 [文件測試](/testing-doc)。
- `build.jobs` 可以設成 `"default"`，恢復預設的平行度。
- rustdoc 搜尋可以用 `[]` 找切片與陣列型別，並在結果名稱後標示項目種類。

### 相容性注意

- `Ipv6Addr` 對 IPv4 相容位址的 `Display` 格式改變，詳見 [std::net](/pkg-net)。
- Cargo 的 feature 名稱字元檢查成為硬性錯誤（1.49 起警告），只影響非 crates.io 的 registry。

### String::leak：換來 'static 的字串切片

有些 API 要求 `&'static str`，但字串是在執行期才組出來的。`String::leak` 放棄這塊記憶體的所有權並回傳 `&'static mut str`，此後程式結束前都不會釋放。適合在程式啟動時建立一次、之後一直使用的設定或名稱表，所有權觀念見 [所有權](/ownership-basics)。

範例：

```rust
fn intern(s: String) -> &'static str {
    s.leak()
}

fn main() {
    let name = intern(format!("user-{}", 42));
    let names: Vec<&'static str> = vec![name, intern("guest".to_string())];
    println!("{names:?}");
}
```

輸出：

```text
["user-42", "guest"]
```

注意：被 leak 的記憶體永遠不會釋放；在迴圈中反覆呼叫會讓記憶體持續增加。

### 用共享參考在多執行緒間使用 Sender

`Sender<T>` 現在是 `Sync`，所以 `&Sender<T>` 可以傳給多條執行緒。搭配 [作用域執行緒](/concurrency-threads)，不必再對每條執行緒 `clone` 一個 `Sender`。所有執行緒結束後丟掉原本的 `tx`，接收端的迭代就會結束；結果先排序以排除執行緒順序的影響。

範例：

```rust
use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();
    thread::scope(|s| {
        for id in 0..3 {
            let tx = &tx;
            s.spawn(move || tx.send(id * 10).unwrap());
        }
    });
    drop(tx);
    let mut got: Vec<i32> = rx.iter().collect();
    got.sort();
    println!("{got:?}");
}
```

輸出：

```text
[0, 10, 20]
```

## 本版新增的棄用 API

本版沒有新增棄用 API。

## 修補版本

| 版本 | 發布日期 | 含安全修補 | 內容（官方原文） |
| --- | --- | --- | --- |
| `1.72.1` | 2023-09-19 | 否 | Adjust codegen change to improve LLVM codegen；rustdoc: Fix self ty params in objects with lifetimes；Fix regression in compile times；Resolve some ICE regressions in the compiler:；#115215；#115559 |

## 已知漏洞

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

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

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

## 資料來源

- [Rust 1.72 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1720-2023-08-24)
- [Rust 1.72 發布公告](https://blog.rust-lang.org/releases/1.72.0/)
- [rust-lang/rust 原始碼 1.72.0](https://github.com/rust-lang/rust/tree/1.72.0)
