# Rust 1.22

Rust 1.22 發布於 2017-11-22，目前最新修補版為 `1.22.1`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.22 的重點是 `?` 運算子可以用在 `Option` 上：值是 `None` 就直接從函式回傳 `None`，一連串「可能沒有值」的步驟不必再層層 `match`。另外 `x += &8` 這種「數值加上參考」的寫法也能編譯了，不用再手動解參考。升級時要注意：這版還不能在同一個函式裡讓 `?` 混用 `Result` 與 `Option`；而 `T op= &T` 的新規則會讓少數原本推論得出來的型別變得無法推論。

### 語言變更

- `Option<T>` 可以使用 `?` 運算子，詳見 [Option](/enums-option)。
- 數值型別支援 `T op= &T`，例如 `let mut x = 2; x += &8;`，詳見 [std::ops](/pkg-ops)。
- 實作 `Drop` 的型別可以放進 `const` 與 `static`，詳見 [常數與靜態變數](/basics-constants)。
- Unicode 跳脫序列裡可以使用底線；`non_snake_case` lint 不再檢查 `extern` 的 `no_mangle` 函式。

### 標準庫重點

- `Box<Error>` 實作 `From<Cow<str>>`，詳見 [std::error](/pkg-error)。
- `mem::Discriminant` 保證是 `Send + Sync`。
- `Instant += Duration` 會正確偵測溢位，詳見 [std::time](/pkg-time)。
- `&mut Hasher` 與 `Box<Hasher>` 實作 `Hasher`，詳見 [std::hash](/pkg-hash)；`SplitWhitespace` 實作 `Debug`。

### Cargo 與工具

- `examples/` 下含 `main.rs` 的子目錄會建置成多檔案範例，詳見 [Cargo](/start-cargo)。
- `Cargo.lock` 的 `[root]` 改為 `[package]`，舊格式仍可用，執行 `cargo update` 會更新。
- 支援把 git 來源的相依 vendor 到本地。
- 文件測試的程式碼區塊可以標記 `compile_fail`，表示這段應該編譯失敗，詳見 [文件測試](/testing-doc)。
- debug 建置預設使用 16 個 codegen unit 且不跨單元內聯，加快編譯；macOS 上的回溯更完整。

### 相容性注意

- `T op= &T` 讓部分型別推論失敗。
- `rustc` 可建置的最低 Android 版本由 2.3 提高到 4.0；移除 PNaCl 目標 `le32-unknown-nacl`。

### Option 的 ? 運算子

`?` 寫在 `Option` 後面時：是 `Some(v)` 就取出 `v` 繼續執行；是 `None` 就讓整個函式立刻回傳 `None`。所以使用 `?` 的函式本身也要回傳 `Option`。需要把 `Result` 接進來時，先用 `.ok()` 把它轉成 `Option`。

範例：

```rust
fn port_of(line: &str) -> Option<u16> {
    let pos = line.find(':')?;
    let digits = line.get(pos + 1..)?;
    digits.trim().parse().ok()
}

fn first_char_upper(words: &[&str]) -> Option<char> {
    let first = words.first()?;
    let c = first.chars().next()?;
    Some(c.to_ascii_uppercase())
}

fn main() {
    println!("{:?}", port_of("localhost: 8080"));
    println!("{:?}", port_of("localhost"));
    println!("{:?}", port_of("localhost:abc"));
    println!("{:?} {:?}", first_char_upper(&["rust", "go"]), first_char_upper(&[]));
}
```

輸出：

```text
Some(8080)
None
None
Some('R') None
```

注意：在回傳 `Result` 的函式裡對 `Option` 用 `?` 會編譯失敗，要先用 `ok_or` 轉成 `Result`，詳見 [錯誤處理實務](/errors-best-practices)。

### 數值的 T op= &T

走訪 `&Vec` 或 `.iter()` 時拿到的是參考 `&i32`。以前累加要寫成 `total += *p`，現在 `+=`、`-=` 等複合指定運算子可以直接接受參考，標準庫為所有數值型別補上了這些實作。

範例：

```rust
fn main() {
    let prices = vec![120, 45, 300];
    let mut total = 0;
    for p in &prices {
        total += p;
    }
    println!("總計：{}", total);

    let mut budget = 1000.0;
    let costs = [250.5, 99.5];
    for c in costs.iter() {
        budget -= c;
    }
    println!("剩餘：{}", budget);
}
```

輸出：

```text
總計：465
剩餘：650
```

注意：這只適用於標準庫的數值型別；自己定義的型別要支援 `+= &T`，需要自行為 `&T` 實作 `AddAssign`。

## 本版新增的棄用 API

本版沒有新增棄用 API。

## 修補版本

| 版本 | 發布日期 | 含安全修補 | 內容（官方原文） |
| --- | --- | --- | --- |
| `1.22.1` | 2017-11-22 | 否 | Update Cargo to fix an issue with macOS 10.13 "High Sierra" |

## 已知漏洞

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

### 仍影響 `1.22.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-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-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.22 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1220-2017-11-22)
- [Rust 1.22 發布公告](https://blog.rust-lang.org/releases/1.22.0/)
- [rust-lang/rust 原始碼 1.22.0](https://github.com/rust-lang/rust/tree/1.22.0)
