# Rust 1.85

Rust 1.85 發布於 2025-02-20，目前最新修補版為 `1.85.1`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.85 是 Rust 2024 edition 的首版，也是官方說明中規模最大的一次 edition。edition 是「選擇加入」的變更機制：只有在 `Cargo.toml` 寫 `edition = "2024"` 的套件才會套用新規則，舊專案不受影響，不同 edition 的 crate 也能互相相依。同一版還穩定了非同步閉包（async closure）`async || {}`。升級時可以執行 `cargo fix --edition` 自動轉換，但它的修改刻意保守，只保證行為不變，不代表建議寫法；`std::env::set_var` 等函式在 2024 edition 變成 `unsafe`。

### 語言變更

- 穩定 2024 edition，各項變更見下方「Rust 2024 edition」，完整的 edition 觀念見 [Edition 演進](/evolution-editions)。
- 穩定非同步閉包 `async |x| ...` 與 `AsyncFn`、`AsyncFnMut`、`AsyncFnOnce` 特徵，`AsyncFn*` 在所有 edition 都加入 prelude，詳見 [非同步基礎](/async-basics) 與 [閉包](/closures-basics)。
- 穩定 `#[diagnostic::do_not_recommend]`，讓特徵 impl 不出現在錯誤訊息的建議中。
- 新增 `unpredictable_function_pointer_comparisons` lint，警告比較函式指標。

### 標準庫重點

- 長度 1 到 12 的元組實作 `FromIterator` 與 `Extend`，可以一次 `collect` 成多個集合，詳見 [迭代器](/pkg-iter)。
- 新增 `std::task::Waker::noop`，詳見 [std::task](/pkg-task)。
- 新增 `ptr::fn_addr_eq`、`BuildHasherDefault::new`，以及浮點數與無號整數的 `midpoint`。
- `io::ErrorKind` 新增 `QuotaExceeded` 與 `CrossesDevices`，詳見 [std::io](/pkg-io)。
- `std::env::home_dir()` 在 Windows 上不再參考非標準的 `HOME` 環境變數，之後的版本會取消它的棄用標記，詳見 [std::env](/pkg-env)。

### Cargo 與工具

- 2024 edition 預設使用會考慮 `rust-version` 的相依解析器，詳見 [Cargo 與套件](/modules-cargo)。
- 2024 edition 的文件測試合併成單一執行檔，大幅加快 `cargo test`，詳見 [文件測試](/testing-doc)。
- rustfmt 新增「style edition」，格式化規則可以和語言 edition 分開設定，詳見 [開發工具](/modules-tools)。
- 建置腳本會收到 `CARGO_CFG_FEATURE` 環境變數。

### 相容性注意

- `rustc` 不再把 `test` 視為已知的 check-cfg，需要時自行加 `--check-cfg=cfg(test)`；Cargo 目前仍會自動設定。
- `core::ffi::c_char` 的正負號改為與平台預設的 `char` 一致，部分 Arm、RISC-V 嵌入式目標會受影響。
- 標準庫 panic 的路徑開頭多了 `library/`。

### Rust 2024 edition

2024 edition 的變更分成幾類，下表列出新手最可能碰到的部分：

| 類別 | 變更 |
| --- | --- |
| 語言 | 回傳位置 `impl Trait` 預設捕捉所有作用域中的泛型與生命週期（可用 `use<..>` 縮小）；`if let` 與區塊結尾運算式的暫存值改為更早 drop |
| 語言 | `extern` 區塊必須寫成 `unsafe extern`；`no_mangle`、`export_name`、`link_section` 屬性必須寫成 `#[unsafe(...)]` |
| 語言 | `unsafe fn` 內的不安全操作要再包 `unsafe {}`（`unsafe_op_in_unsafe_fn` 預設警告）；取得 `static mut` 的參考預設為錯誤 |
| 語言 | 保留 `gen` 關鍵字與 `#"foo"#` 語法；巨集的 `expr` 片段也匹配 `const` 與 `_` 運算式；never 型別 `!` 的推斷退回規則改變 |
| 標準庫 | prelude 加入 `Future` 與 `IntoFuture`；`Box<[T]>` 的 `into_iter` 逐一取出元素的值 |
| 標準庫 | `std::env::set_var`、`std::env::remove_var` 與 Unix 的 `CommandExt::before_exec` 變成 `unsafe` 函式 |
| Cargo／工具 | 依 `rust-version` 解析相依；文件測試合併執行；rustfmt 的 style edition 與排序規則調整 |

下面這段在 2024 edition 無法編譯：`set_var` 會修改整個行程共用的環境變數，在多執行緒程式中可能造成未定義行為，所以必須放進 `unsafe` 區塊，由呼叫者保證沒有其他執行緒同時讀寫環境變數。同一段程式用 `--edition 2021` 編譯仍可通過。

範例：

```rust
fn main() {
    std::env::set_var("APP_MODE", "dev");
}
```

輸出：

```text
error[E0133]: call to unsafe function `set_var` is unsafe and requires unsafe block
 --> main.rs:2:5
  |
2 |     std::env::set_var("APP_MODE", "dev");
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ call to unsafe function
  |
  = note: consult the function's documentation for information on how to avoid undefined behavior
```

改成 `unsafe { std::env::set_var("APP_MODE", "dev"); }` 即可編譯。

### 非同步閉包

`async |x| ...` 是會回傳 future 的閉包，而且回傳的 future 可以借用閉包捕捉的變數；接收端用 `AsyncFn` 約束，就能多次呼叫並 `.await`。下面的 `block_on` 用同版新增的 `Waker::noop` 寫成最簡單的執行器，只為了在不依賴第三方 runtime 的情況下執行範例。

範例：

```rust
use std::future::Future;
use std::pin::pin;
use std::task::{Context, Poll, Waker};

fn block_on<F: Future>(fut: F) -> F::Output {
    let mut fut = pin!(fut);
    let mut cx = Context::from_waker(Waker::noop());
    loop {
        if let Poll::Ready(v) = fut.as_mut().poll(&mut cx) {
            return v;
        }
    }
}

async fn run_twice<F>(f: F) -> u32
where
    F: AsyncFn(u32) -> u32,
{
    f(1).await + f(2).await
}

fn main() {
    let base = 10;
    let add = async |x: u32| x + base;
    println!("{}", block_on(run_twice(add)));
}
```

輸出：

```text
23
```

### 元組的 FromIterator 與 Extend

以前 `unzip` 只能拆成兩個集合；現在元組本身實作了 `FromIterator`，元素是三元組的迭代器可以直接 `collect` 成三個 `Vec`。

範例：

```rust
fn main() {
    let rows = [("Amy", 90, true), ("Bob", 72, false), ("Cid", 85, true)];
    let (names, scores, passed): (Vec<&str>, Vec<u32>, Vec<bool>) = rows.into_iter().collect();
    println!("{:?}", names);
    println!("{:?}", scores);
    println!("{:?}", passed);
}
```

輸出：

```text
["Amy", "Bob", "Cid"]
[90, 72, 85]
[true, false, true]
```

## 本版新增的棄用 API

本版沒有新增棄用 API。

## 修補版本

| 版本 | 發布日期 | 含安全修補 | 內容（官方原文） |
| --- | --- | --- | --- |
| `1.85.1` | 2025-03-18 | 否 | Fix the doctest-merging feature of the 2024 Edition.；Relax some `target_feature` checks when generating docs.；Fix errors in `std::fs::rename` on Windows 10, version 1607.；Downgrade bootstrap `cc` to fix custom targets.；Skip submodule updates when building Rust from a source tarball. |

## 已知漏洞

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

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

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

## 資料來源

- [Rust 1.85 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1850-2025-02-20)
- [Rust 1.85 發布公告](https://blog.rust-lang.org/releases/1.85.0/)
- [rust-lang/rust 原始碼 1.85.0](https://github.com/rust-lang/rust/tree/1.85.0)
