# Rust 1.73

Rust 1.73 發布於 2023-10-05，目前最新修補版為 `1.73.0`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.73 改善了每個人都會看到的 panic 訊息：預設的 panic 處理器把訊息放到獨立一行，不再用引號包起來；`assert_eq!`／`assert_ne!` 的自訂訊息也移到前面、去掉多餘的符號。`thread_local!` 宣告的 `Cell`／`RefCell` 可以直接 `get`、`set`、`take`，不必再寫 `with(|x| ...)`。升級要注意：`invalid_reference_casting` lint 改為預設拒絕，把 `&T` 強制轉成 `&mut T` 的程式會編譯失敗。

### 語言變更

- `invalid_reference_casting` 改為預設拒絕，unsafe 見 [unsafe](/lowlevel-unsafe)。
- `noop_method_call` 預設警告，例如對沒有實作 `Clone` 的參考呼叫 `.clone()`，只是複製了參考。
- 新增 `useless_ptr_null_checks` lint（原 Clippy `fn_null_check`）；`unconditional_recursion` 也能偵測遞迴的 drop。
- 固定長度的不可反駁切片模式會被推論為陣列。

### 標準庫重點

- 預設 panic 訊息改為 `panicked at 檔案:行:欄:` 接下一行訊息，詳見 [panic](/errors-panic) 與 [std::panic](/pkg-panic)。
- `LocalKey<Cell<T>>` 新增 `get`、`set`、`take`、`replace`；`LocalKey<RefCell<T>>` 新增 `with_borrow`、`with_borrow_mut`、`set`、`take`、`replace`，詳見 [std::thread](/pkg-thread) 與 [std::cell](/pkg-cell)。
- 無號整數新增 `div_ceil`、`next_multiple_of`、`checked_next_multiple_of`，詳見 [std::num](/pkg-num)。
- Unix 新增 `std::os::unix::fs::chown`、`fchown`、`lchown`，詳見 [std::fs](/pkg-fs)。
- `Arc<File>` 實作 `Read`、`Write`、`Seek`；`io::Sink` 的功能併入 `io::Empty`；`ExitStatus` 實作 `Default`。
- `rc::Weak::new`、`sync::Weak::new`、`NonNull::as_ref` 可在 const 環境使用。

### Cargo 與工具

- 建置腳本輸出 `cargo::` 開頭的指令時，Cargo 會回報錯誤，見 [Cargo](/modules-cargo)。
- 編譯產物會在 `.comment` 區段寫入版本資訊，與 GCC、Clang 一致。
- `extern "thiscall"` 與 `"thiscall-unwind"` ABI 穩定。

### 相容性注意

- 外部 LLVM 的最低版本提高到 15。
- 會檢查 return position `impl Trait` 的非定義用法，少數程式可能出現新的錯誤。

### 更清楚的 panic 訊息

panic 訊息現在分兩行：第一行是位置，第二行起是訊息本身，訊息裡有引號或換行時更好讀。`assert_eq!` 的格式變成 ``assertion `left == right` failed: 自訂訊息``，再分行列出 `left` 與 `right`。下面用 `panic::set_hook` 印出 panic 資訊（這個格式正是預設處理器在 `thread 'main'` 之後印的內容），再用 `catch_unwind` 接住 panic 讓程式繼續執行。

範例：

```rust
use std::panic;

fn main() {
    panic::set_hook(Box::new(|info| {
        eprintln!("{info}");
    }));
    let r = panic::catch_unwind(|| {
        assert_eq!(1 + 1, 3, "算術出錯了");
    });
    println!("{}", r.is_err());
}
```

輸出：

```text
panicked at main.rs:8:9:
assertion `left == right` failed: 算術出錯了
  left: 2
 right: 3
true
```

注意：預設處理器會在最前面加上 `thread 'main' (<執行緒 ID>)`，執行緒 ID 每次執行都不同；以上輸出的位置以檔名 `main.rs` 編譯為準。

### LocalKey 的 get、set、take

`thread_local!` 的變數型別是 `LocalKey<T>`，以前一律要用 `KEY.with(|v| ...)` 取用。內部是 `Cell` 時，現在可以直接 `KEY.get()`、`KEY.set(v)`；是 `RefCell` 時可以用 `with_borrow`／`with_borrow_mut` 借用，`take` 取走內容並留下預設值。內部可變性見 [std::cell](/pkg-cell)。

範例：

```rust
use std::cell::{Cell, RefCell};

thread_local! {
    static HITS: Cell<u32> = const { Cell::new(0) };
    static LOG: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
}

fn main() {
    HITS.set(HITS.get() + 1);
    HITS.set(HITS.get() + 1);
    LOG.with_borrow_mut(|v| v.push("start".to_string()));
    LOG.with_borrow_mut(|v| v.push("done".to_string()));

    println!("{}", HITS.get());
    LOG.with_borrow(|v| println!("{v:?}"));
    let taken = LOG.take();
    println!("{taken:?} {}", LOG.with_borrow(|v| v.len()));
}
```

輸出：

```text
2
["start", "done"]
["start", "done"] 0
```

### div_ceil 與 next_multiple_of

分頁、分批、記憶體對齊都需要「無條件進位的除法」。`a.div_ceil(b)` 直接算出 ⌈a / b⌉，不用寫 `(a + b - 1) / b` 而擔心溢位；`next_multiple_of(n)` 回傳大於等於自己的最小 n 倍數，`checked_` 版本在結果超出型別範圍時回傳 `None`。

範例：

```rust
fn main() {
    let items: u32 = 23;
    let per_page: u32 = 10;
    println!("{}", items.div_ceil(per_page));

    let offset: u32 = 13;
    println!("{} {}", offset.next_multiple_of(8), 16u32.next_multiple_of(8));
    println!("{:?}", u8::MAX.checked_next_multiple_of(16));
}
```

輸出：

```text
3
16 16
None
```

注意：除數為 `0` 時 `div_ceil` 與 `next_multiple_of` 會 panic；這兩個方法在本版只穩定於無號整數。

## 本版新增的棄用 API

本版沒有新增棄用 API。

## 修補版本

本版沒有修補版本。

## 已知漏洞

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

### 仍影響 `1.73.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) |
| [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.73 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1730-2023-10-05)
- [Rust 1.73 發布公告](https://blog.rust-lang.org/releases/1.73.0/)
- [rust-lang/rust 原始碼 1.73.0](https://github.com/rust-lang/rust/tree/1.73.0)
