# Rust 1.12

Rust 1.12 發布於 2016-09-29，目前最新修補版為 `1.12.1`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.12 被官方稱為 1.0 以來最重要的版本之一。使用者最有感的是全新的錯誤訊息格式：把你的程式碼放在中間，用標註直接指出出錯的位置與原因，也能用 `--error-format=json` 輸出給 IDE 使用的機器可讀格式。內部則改由 MIR（mid-level IR）產生 LLVM IR，為之後的最佳化鋪路；Cargo 也加入了工作區（workspace）。升級要注意：格式化字串指定精確度（precision）時，填充、對齊與寬度不再被忽略；字串的 `Debug` 輸出不再跳脫所有非 ASCII 字元。

### 語言變更

- `macro_rules!` 可以在 `macro_rules!` 呼叫中再呼叫、meta 變數具備衛生性（hygiene），`tt` 比對器能正確重新解析，詳見 [宣告式巨集](/macros-declarative)。
- `macro_rules!` 呼叫內必須用分號分隔陳述式。
- `cfg_attr` 可以套用在 `path` 屬性上。

### 標準庫重點

- `format!` 等巨集可以讓同一個引數以多種樣式格式化，例如 `{0} {0:x}`，詳見 [std::fmt](/pkg-fmt)。
- `String` 實作 `AddAssign`，可以用 `+=` 附加字串切片，詳見 [String](/pkg-string)。
- `Option` 實作 `From<T>`；`Cell`、`RefCell`、`UnsafeCell` 也實作 `From`，詳見 [Option](/pkg-option)。
- `BinaryHeap::peek_mut` 可以直接修改堆積頂端的元素，詳見 [std::collections](/pkg-collections)。
- `Receiver::recv_timeout` 在指定時間內等不到訊息就回傳 `RecvTimeoutError`，詳見 [std::sync::mpsc](/pkg-sync-mpsc)。
- `iter::Sum`、`iter::Product` 特徵穩定，自訂型別也能被 `sum`／`product`，詳見 [std::iter](/pkg-iter)。
- `LinkedList::contains`、`VecDeque::contains`、`Cell::as_ptr` 與 `IpAddr` 的 `is_loopback` 等方法穩定。
- `Cow<str>` 可以從 `char`、`&str`、`String` 的迭代器收集；Unicode 資料更新到 9.0。

### Cargo 與工具

- 新增工作區：多個套件共用同一個 `Cargo.lock`，在頂層 `Cargo.toml` 加上 `[workspace]` 即可啟用，詳見 [工作區](/modules-workspaces)。
- 可以覆寫 crate 的來源，支援本機的 registry 鏡像；新增命令別名。
- `cargo new --lib`、`cargo publish --dry-run`、`RUSTDOCFLAGS` 等新選項，詳見 [Cargo](/modules-cargo)。
- 測試執行檔支援 `--test-threads` 指定執行緒數，效果同 `RUST_TEST_THREADS`；執行超過 60 秒的測試會出現警告，詳見 [單元測試](/testing-unit)。
- 可用 `rustup component add rust-src` 安裝標準庫原始碼，供 IDE 與工具使用，詳見 [安裝](/start-install)。
- 錯誤描述中的參考改用一般英文描述，未知數值型別顯示為 `{integer}` 或 `{float}`。

### 相容性注意

- 格式化指定精確度時，fill、align、width 不再被忽略。
- 字串的 `Debug` 實作不再跳脫所有非 ASCII 字元。
- 在 Windows 印出 `OsStr` 時，未成對的代理碼點以小寫格式跳脫。

### 新的錯誤訊息格式

新格式先顯示錯誤代碼與一句摘要，再列出相關的程式碼行，用 `-` 與 `^` 標記每個位置各自扮演的角色。這段程式碼無法編譯：`first` 借用了 `names` 的元素，之後又要 `push` 修改 `names`，違反借用規則。下面是本書基準版本 rustc 1.100 的實際輸出，版面延續 1.12 引入的格式。

範例：

```rust
fn main() {
    let mut names = vec![String::from("ann")];
    let first = &names[0];
    names.push(String::from("bob"));
    println!("{}", first);
}
```

輸出：

```text
error[E0502]: cannot borrow `names` as mutable because it is also borrowed as immutable
 --> main.rs:4:5
  |
3 |     let first = &names[0];
  |                  ----- immutable borrow occurs here
4 |     names.push(String::from("bob"));
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
5 |     println!("{}", first);
  |                    ----- immutable borrow later used here

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0502`.
```

讀法：`^^^` 是錯誤發生的主要位置，`---` 是相關的位置；照著三個標註由上往下讀，就能看出「先借用、再修改、之後又使用借用」的順序，詳見 [參考與借用](/ownership-references)。

### 同一個引數多種格式與 String +=

格式字串中的 `{0}` 指第一個引數，可以重複引用並套用不同樣式。`String` 支援 `+=` 後，附加字串的寫法更直覺；`Option` 實作 `From<T>`，可以用 `.into()` 把值包成 `Some`。

範例：

```rust
fn main() {
    let n = 255;
    println!("{0} = {0:x} = {0:#b} = {0:?}", n);

    let mut report = String::from("結果：");
    report += "通過";
    report += &format!("（{} 項）", 12);
    println!("{}", report);

    let maybe: Option<i32> = 5.into();
    println!("{:?}", maybe);
}
```

輸出：

```text
255 = ff = 0b11111111 = 255
結果：通過（12 項）
Some(5)
```

### BinaryHeap::peek_mut

`peek_mut` 借出堆積頂端（最大值）的可變參考；修改完、參考被丟棄時，堆積會自動重新調整，維持最大值在頂端。

範例：

```rust
use std::collections::BinaryHeap;

fn main() {
    let mut heap = BinaryHeap::from(vec![3, 9, 5]);
    if let Some(mut top) = heap.peek_mut() {
        *top = 1;
    }
    println!("{:?}", heap.peek());
    println!("{:?}", heap.into_sorted_vec());
}
```

輸出：

```text
Some(5)
[1, 3, 5]
```

## 本版新增的棄用 API

本版沒有新增棄用 API。

## 修補版本

| 版本 | 發布日期 | 含安全修補 | 內容（官方原文） |
| --- | --- | --- | --- |
| `1.12.1` | 2016-10-20 | 否 | ICE: 'rustc' panicked at 'assertion failed: concrete_substs.is_normalized_for_trans()' #36381；Confusion with double negation and booleans；rustc 1.12.0 fails with SIGSEGV in release mode (syn crate 0.8.0)；Rustc 1.12.0 Windows build of `ethcore` crate fails with LLVM error；1.12.0: High memory usage when linking in release mode with debug info；Corrupted memory after updated to 1.12；"Let NullaryConstructor = something;" causes internal compiler error: "tried to overwrite interned AdtDef"；Fix ICE: inject bitcast if types mismatch for invokes/calls/stores；debuginfo: Handle spread_arg case in MIR-trans in a more stable way. |

## 已知漏洞

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

### 仍影響 `1.12.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-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.12 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1120-2016-09-29)
- [Rust 1.12 發布公告](https://blog.rust-lang.org/releases/1.12.0/)
- [rust-lang/rust 原始碼 1.12.0](https://github.com/rust-lang/rust/tree/1.12.0)
