# Rust 1.31

Rust 1.31 發布於 2018-12-06，目前最新修補版為 `1.31.1`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.31 推出第一個 edition 更新 Rust 2018，被官方形容為 1.0 以來最令人興奮的版本。2018 edition 帶來非詞法生命週期（NLL）、簡化的模組路徑，`cargo new` 產生的專案會在 `Cargo.toml` 寫上 `edition = "2018"`；同時 `const fn`、Clippy 與 Rustfmt 1.0 也在這版穩定。對新手來說，借用檢查器變得更聰明，很多以前要繞路的寫法現在直接就能編譯；升級舊專案可以用 `cargo fix` 自動遷移，2015 與 2018 的 crate 也能互相相依。

### 2018 edition

edition 是 Rust 在不破壞相容性的前提下引入新語法的方式，每個 crate 在 `Cargo.toml` 用 `edition` 欄位選擇，沒寫就是 2015。不同 edition 的 crate 可以混用，生態系不會分裂。完整說明見 [Edition 演進](/evolution-editions)。

- 非詞法生命週期（non-lexical lifetimes，NLL）：借用在最後一次使用後就結束，不必等到變數離開作用域；錯誤訊息也改為指出衝突的借用位置。1.31 只在 2018 edition 啟用，之後才回補到 2015，詳見 [參考與借用](/ownership-references)。
- 幾乎不再需要 `extern crate`。
- 巨集可以用 `use` 匯入，不必再寫 `#[macro_use]`。
- 絕對路徑以 crate 名稱開頭，`crate` 關鍵字代表目前的 crate，詳見 [模組系統](/modules-system)。
- `foo.rs` 與 `foo/` 子目錄可以並存，子模組不必再放 `mod.rs`。

### 語言變更

- 函式與 `impl` 標頭可以用 `'_` 省略生命週期，例如 `impl Reader for BufReader<'_> {}`；結構體仍需宣告生命週期，詳見 [生命週期](/ownership-lifetimes)。
- 可以定義與呼叫 `const fn`，在常數情境中於編譯期求值，目前只支援最小子集，詳見 [常數](/basics-constants)。
- 工具 lint 可以加命名空間，例如 `#[allow(clippy::filter_map)]`。
- 模式比對中可以使用括號。
- `#[no_mangle]` 與 `#[export_name]` 可以放在 crate 的任何位置。

### 標準庫重點

- 新增 `slice::chunks_exact`、`slice::rchunks`、`slice::rchunks_exact` 與對應的 `_mut` 版本，以及 `slice::align_to`、`slice::align_to_mut`，詳見 [切片](/pkg-slice)。
- `Option::replace` 放入新值並取回舊值，詳見 [Option](/pkg-option)。
- `u8` 等整數實作 `From<NonZeroU8>` 這類轉換；`&Option<T>` 可以用 `From` 轉成 `Option<&T>`。
- `time::Duration` 可以乘以 `u32`。

### Cargo 與工具

- Clippy 在 stable 上可用（`rustup component add clippy`、`cargo clippy`），並視為 1.0，lint 只會棄用不會移除，詳見 [開發工具](/modules-tools)。
- Rustfmt 1.0 隨版提供（`cargo fmt`），預設選項下的格式化結果保證向後相容，可放心用 `cargo fmt -- --check` 跑在 CI。
- Cargo 改用 HTTP/2 並行下載 crate。
- 可以在 `Cargo.toml` 重新命名相依套件（`package` 鍵），詳見 [Cargo 專案](/modules-cargo)。

### 非詞法生命週期（NLL）

以前的借用檢查以「作用域」計算：`first` 借用了 `scores`，就算後面不再使用 `first`，借用也要持續到區塊結束，`scores.push` 會被拒絕。NLL 改成看「最後一次使用」：`first` 印完之後借用就結束了，接著修改 `scores` 完全合法。這段程式在 2015 edition 的舊編譯器上無法編譯，現在可以直接執行。

範例：

```rust
fn main() {
    let mut scores = vec![70, 85, 90];
    let first = &scores[0];
    println!("第一個分數：{}", first);
    scores.push(100);
    println!("全部分數：{:?}", scores);
}
```

輸出：

```text
第一個分數：70
全部分數：[70, 85, 90, 100]
```

注意：如果在 `push` 之後還使用 `first`，借用就仍在進行中，依舊會得到 `error[E0502]`，NLL 只是不再誤判「已經用完」的借用。

### const fn

在 `fn` 前加上 `const`，函式就能在常數情境中被呼叫，結果在編譯期算好；在一般程式中呼叫時則和普通函式一樣。範例用同一個 `square` 計算常數值與陣列長度。1.31 的 `const fn` 只允許整數運算、比較、建構結構體與陣列、呼叫其他 `const fn` 等最小功能，後續版本才逐步放寬。

範例：

```rust
const fn square(n: u32) -> u32 {
    n * n
}

const AREA: u32 = square(12);
const BUFFER: [u8; square(3) as usize] = [0; square(3) as usize];

fn main() {
    println!("{}", AREA);
    println!("{}", BUFFER.len());
    println!("{}", square(5));
}
```

輸出：

```text
144
9
25
```

### chunks_exact 與 Option::replace

`chunks` 最後一段可能不滿長度；`chunks_exact` 只給剛好滿長度的區塊，剩下的用 `remainder()` 取得，處理固定長度的資料（例如每 3 個位元組一組）更方便。`rchunks` 從尾端開始切。`Option::replace` 則把新值放進去並回傳原本的值。

範例：

```rust
fn main() {
    let data = [1, 2, 3, 4, 5, 6, 7];

    let mut chunks = data.chunks_exact(3);
    for chunk in &mut chunks {
        println!("{:?}", chunk);
    }
    println!("剩下：{:?}", chunks.remainder());

    for chunk in data.rchunks(3) {
        println!("r {:?}", chunk);
    }

    let mut slot = Some(1);
    let old = slot.replace(2);
    println!("{:?} {:?}", old, slot);
}
```

輸出：

```text
[1, 2, 3]
[4, 5, 6]
剩下：[7]
r [5, 6, 7]
r [2, 3, 4]
r [1]
Some(1) Some(2)
```

## 本版新增的棄用 API

本版沒有新增棄用 API。

## 修補版本

| 版本 | 發布日期 | 含安全修補 | 內容（官方原文） |
| --- | --- | --- | --- |
| `1.31.1` | 2018-12-20 | 否 | Fix Rust failing to build on `powerpc-unknown-netbsd`；Fix broken go-to-definition in RLS；Fix infinite loop on hover in RLS |

## 已知漏洞

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

### 仍影響 `1.31.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) |
| [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.31 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1310-2018-12-06)
- [Rust 1.31 發布公告](https://blog.rust-lang.org/releases/1.31.0/)
- [rust-lang/rust 原始碼 1.31.0](https://github.com/rust-lang/rust/tree/1.31.0)
