# Rust 1.40

Rust 1.40 發布於 2019-12-19，目前最新修補版為 `1.40.0`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.40 穩定了 `#[non_exhaustive]` 屬性，函式庫作者可以宣告「之後可能新增欄位或成員」，下游程式就必須預留萬用分支，新增成員不再是破壞性變更。標準庫加入 `todo!()` 巨集、`mem::take`、`Option::flatten` 等日常好用的 API，巨集也能在型別位置與 `extern` 區塊中使用。升級時要注意：2015 edition 中原本只是 NLL 警告的借用問題，從這版起也成為錯誤。

### 語言變更

- 結構體、列舉與列舉成員可以標上 `#[non_exhaustive]`；其他 crate 比對時必須加 `_ => {}` 分支，也無法直接用結構體語法建構，詳見 [列舉](/enums-basics)。
- 元組結構體與元組列舉成員的建構子可以在 `const` 情境中使用。
- 函式式程序巨集可以用在型別位置（`type Generated = macro!();`）與 `extern` 區塊中；程序巨集可以產生 `macro_rules!` 項目，詳見 [程序式巨集](/macros-procedural)。
- `macro_rules!` 的 `meta` 片段可以比對 `#[attr{tokens}]`、`#[attr[tokens]]` 等新屬性語法。

### 標準庫重點

- `todo!()` 標示「還沒寫完」，執行到時會 panic，詳見 [panic](/errors-panic)。
- `mem::take` 取出值並留下 `Default` 預設值，詳見 [std::mem](/pkg-mem)。
- `Option::as_deref`、`Option::as_deref_mut` 把 `Option<String>` 轉成 `Option<&str>` 這類解參考後的參考；`Option::flatten` 把 `Option<Option<T>>` 攤平，詳見 [Option](/pkg-option)。
- `slice::repeat` 把切片重複 n 次組成新的 `Vec`，詳見 [切片](/pkg-slice)。
- `HashMap::get_key_value` 與 `BTreeMap::get_key_value` 同時取得鍵與值，詳見 [HashMap](/pkg-collections-hash-map)。
- `f32`、`f64` 新增 `to_be_bytes`、`from_le_bytes` 等位元組轉換方法；`UdpSocket::peer_addr` 穩定，詳見 [std::net](/pkg-net)。
- 無號整數的 `is_power_of_two` 改為 `const fn`。

### Cargo 與工具

- Cargo 一律顯示警告，不再只在全新建置時才顯示。
- 對虛擬工作區傳入 feature 旗標（`--all-features` 除外）改為錯誤，以前會被忽略。
- `dev-dependencies` 可以不寫 `version` 就發佈。
- `#[cfg(doctest)]` 讓項目只在執行文件測試時編譯，詳見 [文件測試](/testing-doc)。

### 相容性注意

- 2015 edition 原有的 NLL 警告現在都是錯誤。
- `include!` 只會引入檔案中的第一個運算式，沒有引入整個檔案時會發出警告。
- 在函式原型與常數上使用 `#[inline]` 會觸發 `unused_attribute` 警告；在 trait 或 `extern` 區塊其他位置使用則是錯誤。

### mem::take

想從 `&mut self` 裡「拿走」一個欄位時，因為不能讓欄位處於空的狀態，直接移出會編譯失敗。`mem::take` 取出原本的值，同時放入該型別的 `Default` 值（`Vec` 是空向量、`String` 是空字串），常用在清空緩衝區並回傳內容。

範例：

```rust
use std::mem;

#[derive(Debug, Default)]
struct Buffer {
    items: Vec<String>,
}

impl Buffer {
    fn flush(&mut self) -> Vec<String> {
        mem::take(&mut self.items)
    }
}

fn main() {
    let mut buf = Buffer { items: vec!["a".into(), "b".into()] };
    let flushed = buf.flush();
    println!("{:?}", flushed);
    println!("{:?}", buf);
}
```

輸出：

```text
["a", "b"]
Buffer { items: [] }
```

### Option::as_deref、flatten 與 slice::repeat

`Option<String>` 想傳給接受 `Option<&str>` 的函式時，以前要寫 `.as_ref().map(|s| s.as_str())`，現在一個 `as_deref()` 就好。`flatten` 把兩層 `Option` 攤平成一層，外層或內層任一個是 `None` 結果就是 `None`。`repeat` 則把切片重複成新的 `Vec`。

範例：

```rust
fn main() {
    let name: Option<String> = Some(String::from("Ferris"));
    let r: Option<&str> = name.as_deref();
    println!("{:?}", r);

    let nested: Option<Option<i32>> = Some(Some(3));
    println!("{:?}", nested.flatten());
    println!("{:?}", Some(None::<i32>).flatten());

    println!("{:?}", [1, 2].repeat(3));
}
```

輸出：

```text
Some("Ferris")
Some(3)
None
[1, 2, 1, 2, 1, 2]
```

## 本版新增的棄用 API

本版沒有新增棄用 API。

## 修補版本

本版沒有修補版本。

## 已知漏洞

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

### 仍影響 `1.40.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.40 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1400-2019-12-19)
- [Rust 1.40 發布公告](https://blog.rust-lang.org/releases/1.40.0/)
- [rust-lang/rust 原始碼 1.40.0](https://github.com/rust-lang/rust/tree/1.40.0)
