# Rust 1.16

Rust 1.16 發布於 2017-03-16，目前最新修補版為 `1.16.0`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.16 最大的新增是 `cargo check`：只做型別與借用檢查、不產生執行檔，寫程式時想確認「能不能編譯」會快很多。編譯器的拼字建議（「你是不是想寫 `foo`？」）擴大到幾乎所有名稱，對新手看懂錯誤訊息很有幫助。升級時要注意：沒有任何變體的列舉（enum）不能再用萬用字元 `_` 做 match。

### 語言變更

- `Self` 可以出現在 `impl` 標頭與結構建立運算式（如 `Self { x: 1 }`）中，詳見 [方法](/structs-methods)。
- `dead_code` lint 會把型別別名（type alias）納入考量。
- 匯入清單裡 `self` 的語意更一致，詳見 [模組系統](/modules-system)。

### 標準庫重點

- 新增 `str::repeat`、`str::replacen`，詳見 [str](/pkg-str)。
- 新增 `String::insert_str`、`String::split_off`，詳見 [String](/pkg-string)。
- 新增 `Vec::dedup_by`、`Vec::dedup_by_key`，詳見 [Vec](/pkg-vec)。
- 新增 `Result::unwrap_or_default`，詳見 [Result](/pkg-result)。
- 新增 `Duration::checked_add`、`checked_sub`、`checked_mul`、`checked_div`，溢位時回傳 `None`，詳見 [std::time](/pkg-time)。
- 新增 `VecDeque::truncate`、`VecDeque::resize`、`File::set_permissions`，以及 `IpAddr`／`SocketAddr` 的 `is_ipv4`、`is_ipv6`。
- 標準庫所有公開型別都實作了 `Debug`；`writeln!` 可以只寫目的地，單純輸出換行。
- `Result` 實作了 `iter::Sum` 與 `iter::Product`；`&str` 切在字元中間時，panic 訊息會指出是哪個字元。

### Cargo 與工具

- 新增 `cargo check`，只檢查不產生執行檔，詳見 [Cargo](/start-cargo)。
- `cargo build --all`、`cargo doc --all` 一次處理工作區所有成員，詳見 [工作區](/modules-workspaces)。
- 新增 `cargo --version --verbose`；crates.io 支援在 `Cargo.toml` 設定分類（categories）與 CI 徽章。
- `rustc` 新增 `--emit=metadata`，只輸出含 crate 中繼資料的 `.rmeta` 檔，`cargo check` 就是靠它。
- 移除常給出錯誤建議的「consider using an explicit lifetime」提示。

### 相容性注意

- 沒有變體的列舉不能再用萬用字元模式做 match；指向無值型別（uninhabited type）的參考也不能做模式比對，這在 1.15 是意外允許的。
- 重新實作生命週期省略（lifetime elision），修正了少數漏洞，詳見 [生命週期](/ownership-lifetimes)。
- 在 Windows 主控台讀取 `Stdin` 時，Ctrl-Z 會讓 `read()` 返回。

### str::repeat 與 str::replacen

`repeat(n)` 把字串重複 n 次，產生新的 `String`，常用來畫分隔線或補空白。`replace` 會替換所有符合的子字串，`replacen` 多一個參數，只替換前 n 個。

範例：

```rust
fn main() {
    let line = "-".repeat(12);
    println!("{}", line);

    let path = "a/b/c/d";
    println!("{}", path.replacen("/", "::", 2));
    println!("{}", path.replace("/", "::"));
    println!("{}", path.replacen("/", "::", 0));
    println!("{}", line);
}
```

輸出：

```text
------------
a::b::c/d
a::b::c::d
a/b/c/d
------------
```

注意：兩者都回傳新的 `String`，原本的 `&str` 不會改變；`replacen` 的次數給 `0` 就是完全不替換。

### Vec::dedup_by_key 與 dedup_by

`dedup` 會移除「連續重複」的元素。`dedup_by_key` 讓你指定用哪個值判斷是否重複，`dedup_by` 則直接給一個判斷兩個元素是否相同的函式，例如忽略大小寫。

範例：

```rust
fn main() {
    let mut logs = vec![
        ("INFO", "啟動"),
        ("INFO", "連線"),
        ("WARN", "重試"),
        ("WARN", "重試"),
        ("INFO", "完成"),
    ];
    logs.dedup_by_key(|entry| entry.0);
    println!("{:?}", logs);

    let mut words = vec!["Rust", "rust", "RUST", "Go", "go"];
    words.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
    println!("{:?}", words);
}
```

輸出：

```text
[("INFO", "啟動"), ("WARN", "重試"), ("INFO", "完成")]
["Rust", "Go"]
```

注意：只會移除「相鄰」的重複，第二個 `INFO` 前面隔著 `WARN`，所以被保留；要移除所有重複，先排序再 dedup。

### Result::unwrap_or_default

`unwrap_or_default` 在 `Ok` 時取出值，在 `Err` 時改用該型別的預設值（`Default`），例如數字是 `0`、`Vec` 是空的。適合「失敗就當作空值」的情境，又不想寫 `match`，詳見 [Default](/pkg-default)。

範例：

```rust
fn main() {
    let inputs = ["42", "abc", "-7"];
    for s in inputs {
        let n: i32 = s.parse().unwrap_or_default();
        println!("{:>4} -> {}", s, n);
    }

    let missing: Result<Vec<String>, String> = Err(String::from("讀取失敗"));
    println!("{:?}", missing.unwrap_or_default());
}
```

輸出：

```text
  42 -> 42
 abc -> 0
  -7 -> -7
[]
```

注意：錯誤內容會被直接丟掉；如果需要知道為什麼失敗，改用 `match` 或 `?` 處理，詳見 [Result 錯誤處理](/errors-result)。

## 本版新增的棄用 API

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

| 模組 | 項目 | 官方說明 |
| --- | --- | --- |
| `std::net` | [`TcpListener::only_v6`](https://doc.rust-lang.org/std/net/struct.TcpListener.html#method.only_v6) | this option can only be set before the socket is bound |
| `std::net` | [`TcpListener::set_only_v6`](https://doc.rust-lang.org/std/net/struct.TcpListener.html#method.set_only_v6) | this option can only be set before the socket is bound |

## 修補版本

本版沒有修補版本。

## 已知漏洞

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

### 仍影響 `1.16.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-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-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) |
| [CVE-2017-20004](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-20004) | std | MutexGuard\<Cell\<i32\>\> must not be Sync | 早於 1.19.0 | [1.19.0](/rust-1-19) |

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

## 資料來源

- [Rust 1.16 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1160-2017-03-16)
- [Rust 1.16 發布公告](https://blog.rust-lang.org/releases/1.16.0/)
- [rust-lang/rust 原始碼 1.16.0](https://github.com/rust-lang/rust/tree/1.16.0)
