# Rust 1.20

Rust 1.20 發布於 2017-08-31，目前最新修補版為 `1.20.0`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.20 穩定了關聯常數（associated constant）：型別與特徵除了關聯函式之外，也能掛上常數，特徵還能只宣告常數、由實作者決定值。標準庫新增不穩定排序 `sort_unstable` 系列，以及不會 panic 的字串切片 `str::get`。Cargo 把 crates.io 的登入權杖從 `~/.cargo/config` 移到 `~/.cargo/credentials`，方便設成只有自己能讀。

### 語言變更

- 結構、列舉與特徵可以定義關聯常數，詳見 [特徵進階](/traits-advanced)。
- 修正大量巨集相關的錯誤，巨集展開速度提升 29 倍，詳見 [宣告式巨集](/macros-declarative)。
- 編譯失敗時回報的錯誤總數改為全部錯誤，而不是只算失敗的那個階段。

### 標準庫重點

- 新增 `slice::sort_unstable`、`sort_unstable_by`、`sort_unstable_by_key`，詳見 [切片](/pkg-slice)。
- 新增 `str::get`、`str::get_mut`，範圍不合法時回傳 `None` 而不是 panic，詳見 [str](/pkg-str)。
- 新增 `Option::get_or_insert`、`Option::get_or_insert_with`，詳見 [Option](/pkg-option)。
- 新增 `f32`／`f64` 的 `to_bits`、`from_bits`，詳見 [f64 與浮點數](/pkg-f64)。
- 新增 `mem::ManuallyDrop`，手動控制何時執行解構，詳見 [std::mem](/pkg-mem)。
- 新增 `compile_error!` 巨集；`unimplemented!()` 可以附上訊息；`char` 實作 `FromStr`。
- `Ref`、`RefMut`、`MutexGuard` 與 `RwLock` 的守衛（guard）實作 `Display` 與 `Debug`；Unicode 升級到 10.0.0。
- 加入防範 Stack Clash 的措施（stack probe 等），升級即生效。

### Cargo 與工具

- crates.io 權杖改存於 `~/.cargo/credentials`。
- `src/bin/server/main.rs` 這種子目錄形式會建置成名為 `server` 的執行檔，詳見 [Cargo](/start-cargo)。
- `cargo install` 可以用 `--vers` 指定版本；新增 `--no-fail-fast`，benchmark 失敗也繼續跑完。

### 相容性注意

- `f32`／`f64` 的 `is_sign_negative`、`is_sign_positive` 改為會考慮 NaN 的正負號。
- 回傳型別寫 `'static` 的函式，不再能像使用生命週期參數時那樣通用。

### 關聯常數

關聯常數寫在 `impl` 或特徵裡，用 `型別::常數` 取用。特徵可以只宣告 `const SIDES: u32;` 不給值，每個實作各自填入；預設方法裡則可以用 `Self::SIDES` 讀到實作者的值。因為是常數，它也能用在陣列長度這類需要編譯期值的地方。

範例中的 `u8::MAX` 也是關聯常數，不過整數型別的這類常數是 Rust 1.43 起才有的。

範例：

```rust
trait Shape {
    const SIDES: u32;
    const NAME: &'static str;

    fn describe(&self) -> String {
        format!("{} 有 {} 條邊", Self::NAME, Self::SIDES)
    }
}

struct Triangle;
struct Square;

impl Shape for Triangle {
    const SIDES: u32 = 3;
    const NAME: &'static str = "三角形";
}

impl Shape for Square {
    const SIDES: u32 = 4;
    const NAME: &'static str = "正方形";
}

struct Buffer;

impl Buffer {
    const CAPACITY: usize = 4;
}

fn main() {
    println!("{}", Triangle.describe());
    println!("{}", Square.describe());

    let slots = [0u8; Buffer::CAPACITY];
    println!("容量 {}，陣列長度 {}", Buffer::CAPACITY, slots.len());
    println!("u8 最大值：{}", u8::MAX);
}
```

輸出：

```text
三角形 有 3 條邊
正方形 有 4 條邊
容量 4，陣列長度 4
u8 最大值：255
```

注意：實作特徵時漏掉沒有預設值的關聯常數會編譯失敗，和漏掉必要方法一樣。

### sort_unstable 系列

「穩定」排序指的是：比較結果相等的元素，排序後仍維持原本的先後順序。`sort` 是穩定的；`sort_unstable` 不保證這點，但通常更快，而且不需要額外配置記憶體。只要不在意相等元素的順序（例如排數字），就可以選它。

範例：

```rust
fn main() {
    let words = ["rust", "crate", "package", "cargo"];

    let mut stable = words;
    stable.sort_by_key(|w| w.as_bytes()[0]);
    println!("穩定排序：{:?}", stable);

    let mut nums = [42, 7, 19, 3, 25, 7];
    nums.sort_unstable();
    println!("不穩定排序：{:?}", nums);

    let mut by_len = words;
    by_len.sort_unstable_by(|a, b| b.len().cmp(&a.len()).then(a.cmp(b)));
    println!("依長度由長到短：{:?}", by_len);
}
```

輸出：

```text
穩定排序：["crate", "cargo", "package", "rust"]
不穩定排序：[3, 7, 7, 19, 25, 42]
依長度由長到短：["package", "cargo", "crate", "rust"]
```

注意：只用首字母排序時，`crate` 和 `cargo` 算相等；穩定排序保證 `crate` 仍在前，換成 `sort_unstable_by_key` 就沒有這個保證。範例的第三段把比較條件補到完全分出先後，結果才確定。

## 本版新增的棄用 API

本版沒有新增棄用 API。

## 修補版本

本版沒有修補版本。

## 已知漏洞

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

### 仍影響 `1.20.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-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) |
| [CVE-2019-16760](https://github.com/rust-lang/rust/security/advisories/GHSA-phjm-8x66-qw4r) | cargo | Cargo prior to Rust 1.26.0 may download the wrong dependency | 早於 1.26.0 | [1.26.0](/rust-1-26) |
| [CVE-2019-1010299](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-1010299) | std | vec_deque::Iter has unsound Debug implementation | 1.18.0 起，早於 1.30.0 | [1.30.0](/rust-1-30) |
| [CVE-2018-1000657](https://github.com/rust-lang/rust/issues/44800) | std | Buffer overflow vulnerability in VecDeque::reserve() | 1.3.0 起，早於 1.22.0 | [1.22.0](/rust-1-22) |
| [CVE-2018-1000622](https://groups.google.com/forum/#!topic/rustlang-security-announcements/4ybxYLTtXuM) | rustdoc | Uncontrolled search path element vulnerability in rustdoc plugins | 早於 1.27.1 | [1.27.1](/rust-1-27) |
| [CVE-2018-25008](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-25008) | std | Insufficient synchronization in `Arc::get_mut` | 1.3.0 起，早於 1.29.0 | [1.29.0](/rust-1-29) |

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

## 資料來源

- [Rust 1.20 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1200-2017-08-31)
- [Rust 1.20 發布公告](https://blog.rust-lang.org/releases/1.20.0/)
- [rust-lang/rust 原始碼 1.20.0](https://github.com/rust-lang/rust/tree/1.20.0)
