# Rust 1.42

Rust 1.42 發布於 2020-03-12，目前最新修補版為 `1.42.0`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.42 擴充了切片模式，可以用 `..` 比對「剩下的部分」並用 `rest @ ..` 綁定；新增的 `matches!` 巨集把「值是否符合某個模式」寫成一個布林運算式。`Option` 與 `Result` 的 `unwrap`、`expect` 在 panic 時，訊息會指向你呼叫它的那一行，而不是標準庫內部。升級時要注意：`Error::description` 已棄用，請改用 `Display` 或 `to_string`。

### 語言變更

- 切片模式支援子切片，例如 `[first, .., last]` 與 `[head, rest @ ..]`，詳見 [模式](/control-patterns)。
- `#[repr(transparent)]` 可以用在只有一個成員的列舉。
- 外層屬性程序巨集可以用在行內模組上。
- 幾項僅語法層面的變更（如 `impl` 中省略主體的項目），語意上仍會被拒絕，但程序巨集與條件編譯可以解析。

### 標準庫重點

- `matches!` 巨集穩定，支援 `|` 與 `if` 守衛，詳見 [match](/control-match)。
- `Option::{expect, unwrap}` 與 `Result::{expect, expect_err, unwrap, unwrap_err}` 的 panic 訊息指向呼叫的位置，詳見 [panic](/errors-panic)。
- `Condvar::wait_while`、`Condvar::wait_timeout_while`（官方發布說明寫作 `CondVar`） 在條件成立時持續等待，詳見 [共享狀態](/concurrency-shared-state)。
- `DebugMap::key`、`DebugMap::value`、`ManuallyDrop::take`、`ptr::slice_from_raw_parts`、`ptr::slice_from_raw_parts_mut` 穩定。
- `io::Cursor` 實作 `PartialEq` 與 `Eq`；`iter::Empty<T>` 對任何 `T` 都實作 `Send` 與 `Sync`；`Layout::new` 改為 `const fn`。

### Cargo 與工具

- 2018 edition 中 `use proc_macro;` 不再需要先寫 `extern crate proc_macro;`，詳見 [程序式巨集](/macros-procedural)。

### 相容性注意

- `Error::description` 已棄用，使用時會產生警告，詳見 [自訂錯誤](/errors-custom)。
- 32 位元 Apple 目標降級，不再是 tier 1。

### 子切片模式

以前切片模式只能比對固定長度，想支援任意長度就得寫很多分支。現在 `..` 代表「中間任意個元素」，`rest @ ..` 則把那段綁定成一個子切片。範例用一個 `match` 處理空切片、單一元素與多個元素三種情況。

範例：

```rust
fn describe(words: &[&str]) -> String {
    match words {
        [] => String::from("空的"),
        [only] => format!("只有 {}", only),
        [first, .., last] => format!("從 {} 到 {}", first, last),
    }
}

fn main() {
    println!("{}", describe(&[]));
    println!("{}", describe(&["a"]));
    println!("{}", describe(&["a", "b", "c", "d"]));

    if let [head, rest @ ..] = [1, 2, 3].as_slice() {
        println!("{} {:?}", head, rest);
    }
}
```

輸出：

```text
空的
只有 a
從 a 到 d
1 [2, 3]
```

### matches! 巨集

`matches!(值, 模式)` 在值符合模式時回傳 `true`，否則回傳 `false`，等於只有兩個分支的 `match`。它可以加上 `if` 守衛，也能用 `|` 組合多個模式，放在 `filter` 這類需要布林值的地方特別順手。

範例：

```rust
#[derive(Debug)]
enum Status {
    Active(u32),
    Paused,
    Closed,
}

fn main() {
    let list = [Status::Active(3), Status::Paused, Status::Active(0), Status::Closed];
    let busy = list
        .iter()
        .filter(|s| matches!(s, Status::Active(n) if *n > 0))
        .count();
    println!("{}", busy);
    println!("{}", matches!('x', 'a'..='z' | 'A'..='Z'));
    println!("{:?}", list.last());
}
```

輸出：

```text
1
true
Some(Closed)
```

## 本版新增的棄用 API

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

| 模組 | 項目 | 官方說明 |
| --- | --- | --- |
| `std::error` | [`Error::description`](https://doc.rust-lang.org/std/error/trait.Error.html#method.description) | use the Display impl or to_string() |

## 修補版本

本版沒有修補版本。

## 已知漏洞

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

### 仍影響 `1.42.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) |
| [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) |
| [CVE-2021-42574](https://github.com/rust-lang/rust/security/advisories/GHSA-rcv6-wg5m-24v6) | rustc | rustc and bidirectional-override codepoints in source code | 早於 1.56.1 | [1.56.1](/rust-1-56) |
| [CVE-2021-28878](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-28878) | std | Zip may call __iterator_get_unchecked twice with the same index | 1.14.0 起，早於 1.52.0 | [1.52.0](/rust-1-52) |
| [CVE-2021-28879](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-28879) | std | Zip can cause buffer overflow when a consumed Zip iterator is used again | 1.14.0 起，早於 1.52.0 | [1.52.0](/rust-1-52) |
| [CVE-2021-28876](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-28876) | std | Panic safety issue in Zip specialization | 1.14.0 起，早於 1.52.0 | [1.52.0](/rust-1-52) |
| [CVE-2021-28875](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-28875) | std | Logic bug in Read can cause buffer overflow in read_to_end() | 1.20.0 起，早於 1.50.0 | [1.50.0](/rust-1-50) |
| [CVE-2021-28877](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-28877) | std | TrustedRandomAccess specialization composes incorrectly for nested iter::Zips | 1.11.0 起，早於 1.51.0 | [1.51.0](/rust-1-51) |
| [CVE-2020-36323](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-36323) | std | API soundness issue in join() implementation of \[Borrow\<str\>\] | 1.28.0 起，早於 1.52.0 | [1.52.0](/rust-1-52) |
| [CVE-2020-36317](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-36317) | std | String::retain allows safely creating invalid strings when abusing panic | 1.26.0 起，早於 1.49.0 | [1.49.0](/rust-1-49) |
| [CVE-2021-29922](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-29922) | std | Improper Input Validation of octal literals in `std::net` | 早於 1.53.0 | [1.53.0](/rust-1-53) |

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

## 資料來源

- [Rust 1.42 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1420-2020-03-12)
- [Rust 1.42 發布公告](https://blog.rust-lang.org/releases/1.42.0/)
- [rust-lang/rust 原始碼 1.42.0](https://github.com/rust-lang/rust/tree/1.42.0)
