# Rust 1.50

Rust 1.50 發布於 2021-02-11，目前最新修補版為 `1.50.0`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.50 持續朝 const generics 前進：任意長度的陣列實作了 `Index`／`IndexMut`，`[x; N]` 也正式允許重複一個 `const` 值，即使型別沒有實作 `Copy`。標準庫新增 `bool::then`、`clamp`、`RefCell::take` 等日常好用的小工具。對新手來說，「建立 N 個空 `Vec` 的陣列」終於有直接寫法；升級時要注意，在項目後面多寫分號（如 `struct Foo {};`）會產生警告。

### 語言變更

- 陣列重複運算式 `[x; N]` 中的 `x` 可以是 `const` 值，詳見 [元組與陣列](/types-tuples-arrays)。
- 對聯合體中 `ManuallyDrop<T>` 欄位賦值視為安全操作。

### 標準庫重點

- 新增 `bool::then`，條件成立時才產生 `Some(值)`，詳見 [bool 與 char](/types-bool-char)。
- 新增 `Ord::clamp`、`f32::clamp`、`f64::clamp`，把值限制在範圍內，詳見 [比較](/pkg-cmp)。
- 新增 `RefCell::take`，取出內容並留下預設值，詳見 [Cell 與 RefCell](/pkg-cell)。
- 新增 `slice::fill`、`UnsafeCell::get_mut`。
- `hash_map::Entry` 與 `btree_map::Entry` 新增 `or_insert_with_key`，詳見 [HashMap](/pkg-collections-hash-map)。
- 任意長度的陣列實作 `ops::Index`／`IndexMut`；整數的 `pow` 系列、`IpAddr` 與 `Ipv4Addr` 的多數查詢方法成為 `const fn`。
- Unix 上 `Option<File>` 與 `File` 的大小相同（`-1` 不可能是有效的檔案描述符，被拿來表示 `None`），詳見 [std::fs](/pkg-fs)。

### Cargo 與工具

- 新增 `[build.rustc-workspace-wrapper]`，只對工作區成員套用 `rustc` 包裝程式，詳見 [工作區](/modules-workspaces)。
- `cargo:rerun-if-changed` 指定目錄時會掃描整個目錄；`cargo update` 新增 `--workspace`。
- 執行測試會印出總耗時。

### 相容性注意

- 自訂 `panic!` 巨集攔截 panic 的做法不再有效，應改用 `#[panic_handler]`。
- 在同一層覆寫 `forbid` lint 會變成硬錯誤。
- 項目陳述式後面多餘的分號會產生警告。
- 內部屬性 `#![test]` 被視為不穩定，預設透過 `soft_unstable` lint 報錯。

### 重複 const 值建立陣列

`[x; N]` 原本要求 `x` 的型別實作 `Copy`，所以 `[Vec::new(); 3]` 無法編譯。改成先宣告一個 `const`，再寫 `[EMPTY; 3]`，每個元素都是該常數的一份新值。這個行為其實從 1.38 起就意外可用，1.50 正式承認。

範例：

```rust
fn main() {
    const EMPTY: Vec<String> = Vec::new();
    let mut buckets = [EMPTY; 3];
    buckets[0].push(String::from("a"));
    buckets[2].push(String::from("c"));
    println!("{:?}", buckets);
}
```

輸出：

```text
[["a"], [], ["c"]]
```

### bool::then

`cond.then(|| 值)` 在 `cond` 為 `true` 時回傳 `Some(值)`，否則回傳 `None`，閉包只在條件成立時才執行。搭配 `filter_map` 可以同時過濾與轉換，觀念詳見 [迭代器](/iterators-basics)。

範例：

```rust
fn main() {
    let age = 20;
    let label = (age >= 18).then(|| "adult");
    println!("{:?}", label);
    println!("{:?}", (age < 18).then(|| "minor"));

    let even_squares: Vec<u32> = (1..=6).filter_map(|n| (n % 2 == 0).then(|| n * n)).collect();
    println!("{:?}", even_squares);
}
```

輸出：

```text
Some("adult")
None
[4, 16, 36]
```

### clamp、RefCell::take 與 slice::fill

`clamp(min, max)` 把值夾在範圍內；`RefCell::take()` 取走內容並換成型別的預設值；`fill(v)` 把切片每個元素都設成 `v`。

範例：

```rust
use std::cell::RefCell;

fn main() {
    println!("{}", 150.clamp(0, 100));
    println!("{}", (-3).clamp(0, 100));
    println!("{}", 1.5_f64.clamp(0.0, 1.0));

    let log = RefCell::new(vec![String::from("start")]);
    let taken = log.take();
    println!("{:?} {:?}", taken, log.borrow());

    let mut buf = [0u8; 5];
    buf.fill(9);
    println!("{:?}", buf);
}
```

輸出：

```text
100
0
1
["start"] []
[9, 9, 9, 9, 9]
```

## 本版新增的棄用 API

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

| 模組 | 項目 | 官方說明 |
| --- | --- | --- |
| `std::sync::atomic` | [`Atomic::compare_and_swap`](https://doc.rust-lang.org/std/sync/atomic/struct.Atomic.html#method.compare_and_swap) | Use compare_exchange or compare_exchange_weak instead |

## 修補版本

本版沒有修補版本。

## 已知漏洞

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

### 仍影響 `1.50.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-31162](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-31162) | std | Double free in Vec::from_iter specialization when drop panics | 1.48.0 起，早於 1.52.0 | [1.52.0](/rust-1-52) |
| [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-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-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.50 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1500-2021-02-11)
- [Rust 1.50 發布公告](https://blog.rust-lang.org/releases/1.50.0/)
- [rust-lang/rust 原始碼 1.50.0](https://github.com/rust-lang/rust/tree/1.50.0)
