# Rust 1.46

Rust 1.46 發布於 2020-08-27，目前最新修補版為 `1.46.0`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.46 大幅擴充了 `const fn` 能做的事：`if`、`match`、`loop`、`while` 與 `&&`／`||` 都能在編譯期執行，讓更多計算可以在編譯時完成。同一版穩定了 `#[track_caller]`，自己寫的會 panic 的函式也能像 `unwrap` 一樣，把錯誤位置指向呼叫端。對新手來說，常數不再只能是簡單字面值；升級時要注意 Linux 上的 `rustc` 改為動態連結 `libz`。

### 語言變更

- `const fn` 裡可以使用 `if`、`if let`、`match`、`while`、`while let`、`loop` 與 `&&`／`||`，也能轉型成切片 `&[T]`，詳見 [常數](/basics-constants)。
- 函式可以加上 `#[track_caller]`，panic 訊息會顯示呼叫者的位置，詳見 [panic](/errors-panic)。
- 巢狀的元組索引不必再加括號，`x.0.0` 等同 `(x.0).0`，詳見 [元組與陣列](/types-tuples-arrays)。
- `mem::transmute` 可以用在 `static` 與 `const` 中（仍不能用在 `const fn`）。

### 標準庫重點

- 新增 `Option::zip`，把兩個 `Option` 合成一個元組，詳見 [Option](/pkg-option)。
- 新增 `vec::Drain::as_slice`；`mem::forget` 成為 `const fn`。
- `String` 實作 `From<char>`；所有整數型別新增 `leading_ones`、`trailing_ones`，詳見 [數值](/pkg-num)。
- `NonZeroU8` 等非零整數型別實作從一般整數的 `TryFrom`。
- `&[T]` 與 `&mut [T]` 實作 `PartialEq<Vec<T>>`；`(String, u16)` 實作 `ToSocketAddrs`。

### Cargo 與工具

- 編譯時新增環境變數 `CARGO_BIN_NAME`、`CARGO_CRATE_NAME`、`CARGO_PKG_LICENSE`、`CARGO_PKG_LICENSE_FILE`，詳見 [Cargo](/modules-cargo)。

### 相容性注意

- 對實作 `Drop` 的 C 風格列舉做轉型會產生警告，未來將成為錯誤。
- 結構體上的 `#[repr(i128)]`／`#[repr(u128)]` 會編譯失敗，這兩種表示法只允許用在列舉。
- `f32::asinh`／`f64::asinh` 對負數改回傳正確結果。
- Linux 上的 `rustc` 改為動態連結 `libz`，系統需要安裝該函式庫。

### const fn 中的流程控制

`const fn` 是可以在編譯期執行的函式，結果能直接拿來初始化常數。這版起可以在裡面寫迴圈與分支，下面的費氏數列與成績等級都在編譯時就算好。

範例：

```rust
const fn fib(n: u32) -> u64 {
    let mut a = 0;
    let mut b = 1;
    let mut i = 0;
    while i < n {
        let next = a + b;
        a = b;
        b = next;
        i += 1;
    }
    a
}

const fn grade(score: u32) -> char {
    match score {
        90..=100 => 'A',
        80..=89 => 'B',
        _ => if score >= 60 { 'C' } else { 'F' },
    }
}

const FIB_50: u64 = fib(50);
const G: [char; 3] = [grade(95), grade(85), grade(42)];

fn main() {
    println!("fib(50) = {FIB_50}");
    println!("{G:?}");
}
```

輸出：

```text
fib(50) = 12586269025
['A', 'B', 'F']
```

注意：這一版開放的迴圈只有 `while`、`while let` 與 `loop`，所以範例用 `while` 手動計數，而不是 `for`。

### #[track_caller]

加上 `#[track_caller]` 的函式，在裡面呼叫 `std::panic::Location::caller()` 會得到「呼叫這個函式的地方」，而不是函式本身的位置。標準庫的 `unwrap` 就是靠它讓 panic 訊息指向使用者的程式碼。

範例：

```rust
use std::panic::Location;

#[track_caller]
fn checked_div(a: i32, b: i32) -> Option<i32> {
    if b == 0 {
        let loc = Location::caller();
        println!("除以零，呼叫位置在第 {} 行", loc.line());
        return None;
    }
    Some(a / b)
}

fn main() {
    println!("{:?}", checked_div(10, 2));
    println!("{:?}", checked_div(1, 0));
    println!("{:?}", checked_div(7, 0));
}
```

輸出：

```text
Some(5)
除以零，呼叫位置在第 15 行
None
除以零，呼叫位置在第 16 行
None
```

### Option::zip 與巢狀元組索引

`a.zip(b)` 在兩者都是 `Some` 時回傳 `Some((a, b))`，任一個是 `None` 就回傳 `None`，適合「兩個值都要有才繼續」的情境。巢狀元組現在可以直接寫 `nested.1.0`。

範例：

```rust
fn main() {
    let width = Some(3);
    let height = Some(4);
    println!("{:?}", width.zip(height));
    println!("{:?}", width.zip(None::<i32>));

    let nested = ((1, 2), (3, 4));
    println!("{}", nested.1.0);
}
```

輸出：

```text
Some((3, 4))
None
3
```

## 本版新增的棄用 API

本版沒有新增棄用 API。

## 修補版本

本版沒有修補版本。

## 已知漏洞

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

### 仍影響 `1.46.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.46 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1460-2020-08-27)
- [Rust 1.46 發布公告](https://blog.rust-lang.org/releases/1.46.0/)
- [rust-lang/rust 原始碼 1.46.0](https://github.com/rust-lang/rust/tree/1.46.0)
