# Rust 1.59

Rust 1.59 發布於 2022-02-24，目前最新修補版為 `1.59.0`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.59 帶來三個語言層面的改變：解構賦值（destructuring assignment）讓 `(a, b) = (b, a)` 這種寫法成立；const generics 可以有預設值，型別與常數參數也能交錯排列；`asm!` 內嵌組合語言在 x86、x86-64、ARM、AArch64 與 RISC-V 上穩定。對新手來說，交換兩個變數或一次更新多個值不必再借助暫存變數。升級時要注意：為避開已知的錯誤，這版預設關閉增量編譯，可用 `RUSTC_FORCE_INCREMENTAL=1` 開回。

### 語言變更

- 元組、切片與結構體模式可以出現在賦值的左邊，詳見 [變數](/basics-variables) 與 [模式](/control-patterns)。
- const generics 參數可以設定預設值，型別參數與常數參數的順序限制取消，詳見 [泛型](/generics-basics)。
- 在 x86、x86-64、ARM、AArch64、RISC-V 上穩定 `asm!` 與 `global_asm!`，詳見 [unsafe](/lowlevel-unsafe)。

### 標準庫重點

- 新增 `std::thread::available_parallelism`，查詢程式可用的平行度，詳見 [std::thread](/pkg-thread)。
- 新增 `iter::zip` 函式，詳見 [std::iter](/pkg-iter)。
- `u8` 實作 `TryFrom<char>`，錯誤型別為 `char::TryFromCharError`，詳見 [char](/pkg-char)。
- 新增 `Result::copied`、`Result::cloned`，詳見 [Result](/pkg-result)。
- 新增 `ControlFlow::is_break`、`ControlFlow::is_continue`；非零無號整數新增 `is_power_of_two`。
- `[T; N]` 實作 `TryFrom<&mut [T]>`；`ToLowercase`、`ToUppercase` 實作 `DoubleEndedIterator`。

### Cargo 與工具

- profile 新增 `strip` 選項，例如 `[profile.release]` 設 `strip = "debuginfo"` 或 `"symbols"`，縮小發布的執行檔，詳見 [Cargo](/modules-cargo)。
- 相依套件含有未來版本會拒絕的程式碼時，Cargo 會顯示 future-incompat 警告，可用 `cargo report future-incompatibilities` 查看詳情。
- `--release` 可以縮寫為 `-r`；新增 `term.quiet` 設定。
- 穩定新的符號修飾（symbol mangling）格式，需用 `-Csymbol-mangling-version=v0` 選用。

### 相容性注意

- 預設關閉增量編譯，除非設定 `RUSTC_FORCE_INCREMENTAL=1`。
- 在 `#![cfg_attr]` 中寫 `crate_type` 或 `crate_name` 會觸發未來相容性 lint，建議改用命令列旗標。
- `#[no_link]` 不再影響名稱解析，可能暴露新名稱而造成衝突。
- 空切片呼叫 `split_inclusive()` 改為不產生任何元素；`zip` 推進底層迭代器的保證放寬。
- 2021 版次的 `unreachable!` 改為和其他格式化巨集行為一致。

### 解構賦值

以前只有 `let` 能解構，現在對已宣告的變數賦值時也能用元組、切片與結構體模式。最常見的用途是交換變數，或在迴圈中一次更新多個狀態。

範例：

```rust
fn main() {
    let (mut a, mut b) = (1, 2);
    (a, b) = (b, a);
    println!("{a} {b}");

    let (first, last);
    [first, .., last] = [10, 20, 30, 40];
    println!("{first} {last}");

    struct Size { w: u32, h: u32 }
    let (w, h);
    Size { w, h } = Size { w: 1920, h: 1080 };
    println!("{w}x{h}");

    let (mut x, mut y) = (0, 1);
    for _ in 0..5 {
        (x, y) = (y, x + y);
    }
    println!("{x}");
}
```

輸出：

```text
2 1
10 40
1920x1080
5
```

注意：解構賦值不能搭配 `+=` 這類複合賦值運算子。

### const generics 預設值與交錯排列

`const N: usize = 4` 讓使用者不指定長度時自動用 4，`Buffer<u8>` 就等於 `Buffer<u8, 4>`。型別參數也不必全部排在常數參數前面，可以寫成 `<T, const N: usize, U, const M: usize>`。

範例：

```rust
struct Buffer<T, const N: usize = 4> {
    items: [Option<T>; N],
}

impl<T: Copy, const N: usize> Buffer<T, N> {
    fn new() -> Self {
        Buffer { items: [None; N] }
    }
    fn capacity(&self) -> usize {
        N
    }
}

fn pair<T: Copy, const N: usize, U: Copy, const M: usize>(a: [T; N], b: [U; M]) -> usize {
    a.len() * b.len()
}

fn main() {
    let small: Buffer<u8> = Buffer::new();
    let big: Buffer<u8, 16> = Buffer::new();
    println!("{} {}", small.capacity(), big.capacity());
    println!("{}", small.items.iter().all(Option::is_none));
    println!("{}", pair([1, 2, 3], ['a', 'b']));
}
```

輸出：

```text
4 16
true
6
```

### iter::zip、TryFrom<char> for u8 與 available_parallelism

`zip(a, b)` 是 `a.into_iter().zip(b)` 的函式寫法，兩邊都接受任何 `IntoIterator`，長度以較短的為準。`u8::try_from(c)` 在字元碼位不超過 255 時成功。`available_parallelism()` 回傳 `io::Result<NonZeroUsize>`，數值依機器而異，範例只印出是否至少為 1。

範例：

```rust
use std::iter::zip;

fn main() {
    let names = ["a", "b", "c"];
    let scores = [90, 85];
    for (n, s) in zip(names, scores) {
        println!("{n}: {s}");
    }

    println!("{:?}", u8::try_from('A'));
    println!("{:?}", u8::try_from('中').is_err());
    if let Err(e) = u8::try_from('中') {
        println!("{e}");
    }

    let cores = std::thread::available_parallelism().map(|n| n.get() >= 1);
    println!("{:?}", cores);
}
```

輸出：

```text
a: 90
b: 85
Ok(65)
true
unicode code point out of range
Ok(true)
```

## 本版新增的棄用 API

以下 API 從 Rust 1.59 起標記為棄用（deprecated），新程式不要再使用；說明欄為官方原文。

| 模組 | 項目 | 官方說明 |
| --- | --- | --- |
| `std::array` | [`IntoIter::new`](https://doc.rust-lang.org/std/array/struct.IntoIter.html#method.new) | use IntoIterator::into_iter instead |

## 修補版本

本版沒有修補版本。

## 已知漏洞

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

### 仍影響 `1.59.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-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.59 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1590-2022-02-24)
- [Rust 1.59 發布公告](https://blog.rust-lang.org/releases/1.59.0/)
- [rust-lang/rust 原始碼 1.59.0](https://github.com/rust-lang/rust/tree/1.59.0)
