# Rust 1.58

Rust 1.58 發布於 2022-01-13，目前最新修補版為 `1.58.1`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.58 讓格式字串可以直接捕捉同一範圍內的變數，`println!("{name}")` 不必再寫成 `println!("{}", name)`。標準庫在這版完成 `#[must_use]` 的全面檢查，忽略「回傳新值而不是原地修改」的函式結果時會收到警告。對新手來說，格式化輸出變得更好讀；升級時要注意 Windows 上 `std::process::Command` 不再從目前目錄搜尋執行檔，所有程序式巨集的向後相容 lint 也改為預設拒絕（deny）。

### 語言變更

- 格式字串可以用 `{ident}` 捕捉周圍的變數，所有接受格式字串的巨集都適用，詳見 [std::fmt](/pkg-fmt)。
- `const` 情境中可以解參考 `*const T` 指標。
- 泛型結構體實作 `Unsize` 的規則放寬。

### 標準庫重點

- 標準庫剩下的函式都在適當處加上 `#[must_use]`。
- 新增 `File::options`，取得設定開檔方式的 `OpenOptions`，詳見 [std::fs](/pkg-fs)。
- 新增 `Path::is_symlink`、`Metadata::is_symlink`，詳見 [std::path](/pkg-path)。
- 所有整數新增 `saturating_div`，詳見 [數值](/pkg-num)。
- 新增 `Option::unwrap_unchecked`、`Result::unwrap_unchecked`、`Result::unwrap_err_unchecked`，屬於 `unsafe` 函式，詳見 [unsafe](/lowlevel-unsafe)。
- `Duration::new` 與 `checked_add` 等運算可以在 `const` 中使用，詳見 [std::time](/pkg-time)。
- `main` 可以回傳 `Result<Infallible, E>`，適合從不正常返回的程式。

### Cargo 與工具

- `rustc` 穩定 `-C strip`，可以移除除錯符號縮小執行檔（Cargo 的對應選項在 1.59 加入）。
- `cargo install` 新增 `--message-format`；別名遮蔽外部子指令時會警告。
- rustdoc 會遞迴顯示所有 `Deref` 實作。

### 相容性注意

- Windows 上 `std::process::Command` 不再搜尋目前目錄中的執行檔，詳見 [std::process](/pkg-process)。
- 方法解析時先嘗試所有 stable 的候選方法，再考慮 unstable 的，避免標準庫新增 nightly 方法時和外部特徵的同名方法衝突。
- 所有程序式巨集的向後相容 lint 改為預設 deny。
- rustdoc 會拒絕文件測試中部分不預期的分號。

### 格式字串捕捉變數

在 `{}` 裡直接寫變數名稱，就會捕捉同一範圍的變數；寬度與精度參數也能寫成 `width$`、`precision$` 捕捉變數。只能捕捉單純的識別字，欄位存取或運算式（如 `{p.x}`）仍要用位置參數或 `name = expr` 寫法。

範例：

```rust
fn main() {
    let name = "Ferris";
    let age = 7;
    println!("{name} is {age} years old");

    let pi = 3.14159;
    let width = 10;
    let precision = 2;
    println!("[{pi:>width$.precision$}]");
    println!("{name:?} {age:03}");

    let msg = format!("{name}-{age}");
    println!("{msg}");
}
```

輸出：

```text
Ferris is 7 years old
[      3.14]
"Ferris" 007
Ferris-7
```

注意：在 2015 與 2018 版次中，`panic!("{ident}")` 仍被當成普通字串而不會捕捉變數，編譯器會發出警告；2021 版次起 `panic!` 也和 `println!` 行為一致，詳見 [版次演進](/evolution-editions)。

### File::options

`File::options()` 回傳 `OpenOptions`，用鏈式呼叫設定「建立、附加、截斷」等開檔方式，不必另外匯入 `OpenOptions`。範例在暫存目錄建立檔案、附加兩行再讀回，結束時刪除目錄；`is_symlink()` 同樣是這版新增。

範例：

```rust
use std::fs::{self, File};
use std::io::{Read, Write};

fn main() -> std::io::Result<()> {
    let dir = std::env::temp_dir().join(format!("rust158-{}", std::process::id()));
    fs::create_dir_all(&dir)?;
    let path = dir.join("log.txt");

    let mut f = File::options().create(true).append(true).open(&path)?;
    writeln!(f, "first")?;
    let mut f = File::options().append(true).open(&path)?;
    writeln!(f, "second")?;

    let mut text = String::new();
    File::open(&path)?.read_to_string(&mut text)?;
    print!("{text}");
    println!("{}", path.is_symlink());

    fs::remove_dir_all(&dir)?;
    Ok(())
}
```

輸出：

```text
first
second
false
```

### saturating_div

`saturating_div` 在結果溢位時回傳型別的極值。`i32::MIN / -1` 的結果超出 `i32` 範圍，`saturating_div` 回傳 `i32::MAX`，對照 `checked_div` 則回傳 `None`。

範例：

```rust
fn main() {
    println!("{}", 7_i32.saturating_div(2));
    println!("{}", i32::MIN.saturating_div(-1));
    println!("{:?}", i32::MIN.checked_div(-1));
}
```

輸出：

```text
3
2147483647
None
```

## 本版新增的棄用 API

本版沒有新增棄用 API。

## 修補版本

| 版本 | 發布日期 | 含安全修補 | 內容（官方原文） |
| --- | --- | --- | --- |
| `1.58.1` | 2022-01-20 | 是 | Fix race condition in `std::fs::remove_dir_all` ([CVE-2022-21658])；Handle captured arguments in the `useless_format` Clippy lint；Move `non_send_fields_in_send_ty` Clippy lint to nursery；Fix wrong error message displayed when some imports are missing；Fix rustfmt not formatting generated files from stdin |

## 已知漏洞

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

### 本版已修正

| 編號 | 元件 | 摘要（官方原文） | 影響範圍 | 修正於 |
| --- | --- | --- | --- | --- |
| [CVE-2022-21658](https://github.com/rust-lang/rust/security/advisories/GHSA-r9cc-f5pr-p3j2) | std | Race condition in std::fs::remove_dir_all | 早於 1.58.1 | [1.58.1](/rust-1-58) |

### 仍影響 `1.58.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) |
| [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) |
| [CVE-2022-46176](https://github.com/rust-lang/cargo/security/advisories/GHSA-r5w3-xm58-jv6j) | cargo | Cargo did not verify SSH host keys | 早於 1.66.1 | [1.66.1](/rust-1-66) |
| [CVE-2022-36113](https://github.com/rust-lang/cargo/security/advisories/GHSA-rfj2-q3h3-hm5j) | cargo | Extracting malicious crates can corrupt arbitrary files | 早於 1.64.0 | [1.64.0](/rust-1-64) |
| [CVE-2022-36114](https://github.com/rust-lang/cargo/security/advisories/GHSA-2hvr-h6gw-qrxp) | cargo | Extracting malicious crates can fill the file system | 早於 1.64.0 | [1.64.0](/rust-1-64) |

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

## 資料來源

- [Rust 1.58 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1580-2022-01-13)
- [Rust 1.58 發布公告](https://blog.rust-lang.org/releases/1.58.0/)
- [rust-lang/rust 原始碼 1.58.0](https://github.com/rust-lang/rust/tree/1.58.0)
