# Rust 1.74

Rust 1.74 發布於 2023-11-16，目前最新修補版為 `1.74.1`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.74 讓 `Cargo.toml` 可以用 `[lints]` 表設定 lint 等級，不必再在每個 crate 根部寫 `#![deny(...)]` 或透過 `RUSTFLAGS` 影響整個建置；Cargo 也加入憑證提供者（credential provider）與需要驗證的私有 registry。語言方面，`async fn` 與 `-> impl Trait` 的回傳型別終於可以提到 `Self` 與關聯型別。升級要注意：新的 `From<&[T; N]> for Vec<T>` 可能讓過度泛型的程式型別推論失敗；Apple 平台的最低系統版本提高。

### 語言變更

- 不透明回傳型別（`async fn`、`-> impl Trait`）可以提到 `Self` 與帶父層生命週期的關聯型別，詳見 [進階特徵](/traits-advanced)。
- `private_in_public` lint 被 `private_interfaces` 與 `private_bounds` 取代，模組可見性見 [模組系統](/modules-system)。
- 允許明確寫出 `#[repr(Rust)]`；`async` 區塊改用以 MIR 為基礎的 drop 追蹤。

### 標準庫重點

- `core::num::Saturating` 穩定：運算溢位時停在最大或最小值，詳見 [std::num](/pkg-num)。
- `std::io::Error::other` 用任意錯誤建立 `ErrorKind::Other` 的 I/O 錯誤，詳見 [std::io](/pkg-io) 與 [自訂錯誤](/errors-custom)。
- `Vec<T>` 可從 `&[T; N]`、`&mut [T; N]` 轉換；`Rc<[T]>`、`Arc<[T]>` 可從 `[T; N]` 轉換，詳見 [Vec](/pkg-vec)。
- `OsStr::as_encoded_bytes`、`OsString::into_encoded_bytes` 與對應的 `from_encoded_bytes_unchecked` 穩定，詳見 [std::ffi](/pkg-ffi)。
- `io::Stdout`、`io::Stderr` 可以轉成 `process::Stdio`，讓子行程直接寫到父行程的輸出，詳見 [std::process](/pkg-process)。
- `char` 可用 `TryFrom` 轉成 `u16`；`str::is_ascii` 與 `mem::transmute_copy` 可在 const 環境使用。

### Cargo 與工具

- `Cargo.toml` 新增 `[lints.rust]`、`[lints.clippy]` 等表，也能放在 `[workspace.lints]` 由成員以 `[lints] workspace = true` 繼承，詳見 [Cargo](/modules-cargo) 與 [工作區](/modules-workspaces)。
- 憑證提供者與 registry 驗證穩定：可用作業系統的安全儲存保管 token，私有 registry 可要求所有操作都需驗證。
- `--keep-going` 建置參數穩定；`cargo clean` 新增 `--dry-run`，`-n` 是 `--dry-run` 的別名。
- `cargo update` 的套件名稱可直接當位置參數；`--aggressive` 更名為 `--recursive`；`--help` 輸出加上樣式。

### 相容性注意

- `impl From<{&,&mut} [T; N]> for Vec<T>` 可能讓過度泛型的程式（例如搭配 `AsRef` 與 `Into<Vec>`）型別推論失敗。
- `Cell::swap` 在兩個 `Cell` 部分重疊時會 panic。
- Apple 平台的最低支援系統版本提高；`--extern` 拒絕無效的 crate 名稱。

### Saturating：會「停住」的整數

血量、庫存、音量這類值，減到底就該停在 0，加到頂就該停在上限。`Saturating<T>` 包住整數後，`+`、`-`、`+=` 等運算一律飽和計算，不會溢位也不會 panic；`.0` 取回內部的值。它與 `Wrapping<T>`（溢位時繞回）是一對，整數溢位的觀念見 [整數](/types-integers)。

範例：

```rust
use std::num::Saturating;

fn main() {
    let mut hp = Saturating(10u8);
    hp -= 30;
    println!("{hp}");
    hp += Saturating(250);
    hp += Saturating(250);
    println!("{} {}", hp, hp.0);
}
```

輸出：

```text
0
255 255
```

### io::Error::other：把任何錯誤包成 I/O 錯誤

函式回傳 `io::Result<T>` 時，常需要把別種錯誤（例如解析錯誤）轉進來。以前寫 `io::Error::new(io::ErrorKind::Other, e)`，現在 `io::Error::other(e)` 一步完成，也能直接傳給 `map_err`。原本的錯誤會保留，`Display` 時印出它的訊息。

範例：

```rust
use std::io;

fn read_port(s: &str) -> io::Result<u16> {
    s.parse::<u16>().map_err(io::Error::other)
}

fn main() {
    println!("{:?}", read_port("8080").ok());
    let err = read_port("99999").unwrap_err();
    println!("{:?} {}", err.kind(), err);
}
```

輸出：

```text
Some(8080)
Other number too large to fit in target type
```

### 不透明回傳型別可以提到 Self 與關聯型別

以前在帶生命週期參數的型別上，`-> impl Iterator<Item = Self>` 或 `-> impl Iterator<Item = S::Key>` 會得到「return type cannot contain a projection or `Self` that references lifetimes from a parent scope」錯誤，只能改寫出完整型別名稱。從這版起，下面兩種寫法都能直接編譯：`View<'a, S>` 回傳關聯型別 `S::Key` 的迭代器，`Word<'a>` 回傳 `Self` 的迭代器。

範例：

```rust
trait Store {
    type Key;
    fn keys(&self) -> Vec<Self::Key>;
}

struct Users(Vec<u32>);

impl Store for Users {
    type Key = u32;
    fn keys(&self) -> Vec<u32> {
        self.0.clone()
    }
}

struct View<'a, S: Store>(&'a S);

impl<'a, S: Store> View<'a, S> {
    fn iter_keys(&self) -> impl Iterator<Item = S::Key> {
        self.0.keys().into_iter()
    }
}

struct Word<'a>(&'a str);

impl<'a> Word<'a> {
    fn split(text: &'a str) -> impl Iterator<Item = Self> {
        text.split_whitespace().map(Word)
    }
}

fn main() {
    let users = Users(vec![7, 3, 9]);
    let v = View(&users);
    println!("{:?}", v.iter_keys().collect::<Vec<_>>());
    let lens: Vec<usize> = Word::split("hello rust world").map(|w| w.0.len()).collect();
    println!("{lens:?}");
}
```

輸出：

```text
[7, 3, 9]
[5, 4, 5]
```

## 本版新增的棄用 API

本版沒有新增棄用 API。

## 修補版本

| 版本 | 發布日期 | 含安全修補 | 內容（官方原文） |
| --- | --- | --- | --- |
| `1.74.1` | 2023-12-07 | 否 | Resolved spurious STATUS_ACCESS_VIOLATIONs in LLVM；Clarify guarantees for std::mem::discriminant；Fix some subtyping-related regressions |

## 已知漏洞

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

### 仍影響 `1.74.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.74 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1740-2023-11-16)
- [Rust 1.74 發布公告](https://blog.rust-lang.org/releases/1.74.0/)
- [rust-lang/rust 原始碼 1.74.0](https://github.com/rust-lang/rust/tree/1.74.0)
