# Rust 1.70

Rust 1.70 發布於 2023-06-01，目前最新修補版為 `1.70.0`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.70 有兩個影響很廣的變化：Cargo 讀取 crates.io 索引預設改用 sparse 協定，抓取相依資訊大幅加快；標準庫加入 `OnceCell` 與執行緒安全的 `OnceLock`，一次性初始化的全域資料不再需要 `lazy_static` 或 `once_cell` 套件。另外還有判斷是否連到終端機的 `IsTerminal`，以及 `Option::is_some_and` 這類好用的小方法。升級要注意：受限網路環境必須能連到 `https://index.crates.io`；穩定版的測試執行檔不再接受 `-Zunstable-options` 之類的不穩定選項。

### 語言變更

- 新增 lint 警告有歧義的 glob 重新匯出（re-export），模組見 [模組系統](/modules-system)。
- `let _ = expr` 位置的運算式也會做 const 與 unsafe 檢查。
- debug 模式會在解參考裸指標時插入對齊檢查，抓出未定義行為；既有的錯誤程式可能因此在執行期失敗。

### 標準庫重點

- `std::cell::OnceCell` 與 `std::sync::OnceLock` 穩定，詳見 [std::cell](/pkg-cell) 與 [std::sync](/pkg-sync)。
- `std::io::IsTerminal` 提供 `is_terminal()`，判斷輸出是否接到終端機，詳見 [std::io](/pkg-io)。
- `Option::is_some_and`、`Result::is_ok_and`、`Result::is_err_and` 穩定，詳見 [std::option](/pkg-option) 與 [std::result](/pkg-result)。
- `Rc::into_inner`、`Arc::into_inner` 在只剩最後一個參考時取回內部的值，詳見 [std::rc](/pkg-rc)。
- `BinaryHeap::retain`、`NonZero*::MIN`／`MAX`、`Atomic*::as_ptr` 穩定，多數集合與迭代器的迭代器型別實作 `Default`。

### Cargo 與工具

- crates.io 預設使用 sparse 協定；改用後套件快取路徑不同，相依會重新下載，舊的 `$CARGO_HOME/registry/*/github.com-*` 可以清掉，詳見 [Cargo](/modules-cargo)。
- `-Cdebuginfo` 可以用名稱指定等級：`none`、`limited`、`full`，並新增 `line-directives-only`、`line-tables-only`。
- `cargo logout` 穩定；新增 `CARGO_PKG_README` 環境變數。

### 相容性注意

- 穩定版的 libtest 不再接受 `-Zunstable-options`，依賴 `--format json` 的 IDE 外掛需要調整，測試見 [單元測試](/testing-unit)。
- WebAssembly 目標預設啟用 `sign-ext` 與 `mutable-globals`，舊的執行環境可能不相容。

### OnceLock：只初始化一次的全域值

`static` 的初始值必須在編譯期算出來，`HashMap` 這類需要執行期建構的值放不進去。`OnceLock` 讓你先宣告一個空的 `static`，第一次呼叫 `get_or_init` 時才執行初始化，之後所有執行緒都拿到同一份值；就算多個執行緒同時呼叫，初始化也只會跑一次。單執行緒、不需要放在 `static` 的情境改用 `OnceCell`。

範例：

```rust
use std::collections::HashMap;
use std::sync::OnceLock;
use std::thread;

fn config() -> &'static HashMap<&'static str, u32> {
    static CONFIG: OnceLock<HashMap<&str, u32>> = OnceLock::new();
    CONFIG.get_or_init(|| {
        println!("載入設定（只會出現一次）");
        HashMap::from([("workers", 4), ("timeout", 30)])
    })
}

fn main() {
    let values: Vec<u32> = thread::scope(|s| {
        let hs: Vec<_> = (0..3).map(|_| s.spawn(|| config()["workers"])).collect();
        hs.into_iter().map(|h| h.join().unwrap()).collect()
    });
    println!("{values:?} {}", config()["timeout"]);
}
```

輸出：

```text
載入設定（只會出現一次）
[4, 4, 4] 30
```

### is_some_and、is_ok_and 與 Rc::into_inner

`opt.is_some_and(|v| 條件)` 等於「有值而且值符合條件」，取代 `matches!(opt, Some(v) if 條件)` 或 `map_or(false, ...)`。`Result` 對應的是 `is_ok_and` 與 `is_err_and`。這些方法會取得所有權，想保留原值就先 `.as_ref()`。`Rc::into_inner` 則在參考計數降到 0 時回傳 `Some(值)`，其他情況回傳 `None` 並讓計數減一。

範例：

```rust
use std::rc::Rc;

fn main() {
    let port: Option<u16> = Some(8080);
    println!("{}", port.is_some_and(|p| p >= 1024));

    let parsed: Result<i32, _> = "-7".parse::<i32>();
    println!("{}", parsed.as_ref().is_ok_and(|&n| n > 0));
    println!("{}", "abc".parse::<i32>().is_err_and(|e| e.to_string().contains("invalid")));

    let a = Rc::new(String::from("shared"));
    let b = Rc::clone(&a);
    println!("{:?}", Rc::into_inner(a));
    println!("{:?}", Rc::into_inner(b));
}
```

輸出：

```text
true
false
true
None
Some("shared")
```

## 本版新增的棄用 API

本版沒有新增棄用 API。

## 修補版本

本版沒有修補版本。

## 已知漏洞

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

### 仍影響 `1.70.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) |
| [CVE-2023-40030](https://github.com/rust-lang/cargo/security/advisories/GHSA-wrrj-h57r-vx9p) | cargo | Malicious dependencies can inject arbitrary JavaScript into cargo-generated timing reports | 1.60.0 起，早於 1.72.0 | [1.72.0](/rust-1-72) |
| [CVE-2023-38497](https://github.com/rust-lang/cargo/security/advisories/GHSA-j3xp-wfr4-hx87) | cargo | Cargo not respecting umask when extracting crate archives | 早於 1.71.1 | [1.71.1](/rust-1-71) |

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

## 資料來源

- [Rust 1.70 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1700-2023-06-01)
- [Rust 1.70 發布公告](https://blog.rust-lang.org/releases/1.70.0/)
- [rust-lang/rust 原始碼 1.70.0](https://github.com/rust-lang/rust/tree/1.70.0)
