# Rust 1.2

Rust 1.2 發布於 2015-08-07，目前最新修補版為 `1.2.0`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.2 完成了動態大小型別（dynamically-sized type，DST）的轉型（coercion）：`Rc`、`Arc` 等智慧指標可以裝陣列切片與特徵物件，`Rc<[T]>` 終於能正常使用。編譯器整體變快（hyper 快 1.16 倍、regex 快 1.32 倍），平行程式碼產生（parallel codegen）也恢復運作，Cargo 的無變更建置從 5 秒降到 0.5 秒（以 Servo 為例）。升級要注意：`char` 的 `to_uppercase`／`to_lowercase` 改為完整的 Unicode 大小寫對應，非 ASCII 字元的結果可能和以前不同。

### 語言變更

- 動態大小型別轉型完成，智慧指標可以指向沒有固定大小的型別，例如 `Rc<[T]>` 與 `Rc<dyn Trait>`，詳見 [Rc](/pkg-rc) 與 [特徵物件](/traits-objects)。
- 帶 `ref mut` 的模式在比對可解參考（dereference）的值時，會正確呼叫 `DerefMut`，詳見 [模式](/control-patterns)。

### 標準庫重點

- 新增 `iter::once`（只產生一個元素）與 `iter::empty`（不產生元素），詳見 [std::iter](/pkg-iter)。
- `str` 新增 `to_uppercase`、`to_lowercase`、`matches`、`rmatches`，詳見 [&str](/pkg-str)。
- `fmt::Formatter` 新增 `debug_struct`、`debug_tuple`、`debug_list`、`debug_set`、`debug_map`，`{:#?}` 會以多行縮排顯示 `Debug` 輸出，詳見 [std::fmt](/pkg-fmt)。
- `Extend` 特徵支援參考的迭代器，`Vec`、`String`、`BTreeMap` 等都能 `extend` 一串 `&T`，詳見 [Vec](/pkg-vec)。
- 整數新增 `wrapping_div`、`wrapping_rem`、`wrapping_neg`、`wrapping_shl`、`wrapping_shr`，詳見 [std::num](/pkg-num)。
- `PoisonError` 提供 `into_inner`、`get_ref`、`get_mut`，中毒（poisoned）的鎖也能繼續使用；`Mutex`、`RwLock` 新增 `is_poisoned`，詳見 [std::sync](/pkg-sync)。
- `io::ErrorKind` 新增 `InvalidData` 變體，表示輸入格式錯誤，詳見 [std::io](/pkg-io)。
- `Cell` 與 `RefCell` 實作 `Eq`，詳見 [std::cell](/pkg-cell)。

### Cargo 與工具

- 平行程式碼產生恢復運作，用 `rustc -C codegen-units=N` 啟用，在 4 核心機器上自舉快 33%。
- Cargo 支援共用的 target 目錄，跨多個套件快取相依，詳見 [Cargo](/modules-cargo)。
- 首次以實驗方式支援 Windows 上的 MSVC 連結器與 C 函式庫（取代 MinGW 的 GNU 工具）；目前 panic 時直接中止，尚不支援 unwinding。

### 相容性注意

- `char::to_uppercase`／`to_lowercase` 改用 Unicode 大小寫對應，官方視為 bug 修正。
- `mem::align_of` 改為回傳最小對齊（minimum alignment），與 clang 的 `alignof` 一致，詳見 [std::mem](/pkg-mem)。
- 原本什麼也不做的 `#[packed]` 屬性不再被默默接受。
- 關聯型別預設值改放在 `associated_type_defaults` 功能閘（feature gate）之後。

### Rc 指向切片與特徵物件

`Rc<[i32]>` 是「共享一段長度在執行期才知道的陣列」，`Rc<dyn Display>` 是「共享某個實作 `Display` 的值」。兩者都靠 DST 轉型：先建立固定大小的值，再讓編譯器自動轉成不定大小的版本。

範例：

```rust
use std::fmt::Display;
use std::rc::Rc;

fn main() {
    let nums: Rc<[i32]> = Rc::new([1, 2, 3]);
    let shared = Rc::clone(&nums);
    println!("{:?} 長度 {}，引用數 {}", shared, shared.len(), Rc::strong_count(&nums));

    let items: Vec<Rc<dyn Display>> = vec![Rc::new(42), Rc::new("hello"), Rc::new(1.5)];
    for item in &items {
        println!("{}", item);
    }
}
```

輸出：

```text
[1, 2, 3] 長度 3，引用數 2
42
hello
1.5
```

### 用 debug_struct 自訂 Debug 輸出

`#[derive(Debug)]` 會印出所有欄位；想隱藏敏感欄位時，可以手動實作 `Debug` 並用 `debug_struct` 組出輸出。用 builder 產生的結果自動支援 `{:#?}` 的多行格式，不必自己處理縮排。

範例：

```rust
use std::fmt;

struct Config {
    name: String,
    port: u16,
    secret: String,
}

impl fmt::Debug for Config {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Config")
            .field("name", &self.name)
            .field("port", &self.port)
            .field("secret", &"***")
            .finish()
    }
}

fn main() {
    let c = Config { name: "api".to_string(), port: 8080, secret: "s3cr3t".to_string() };
    println!("{:?}", c);
    println!("{:#?}", c);
    println!("密碼長度 {}", c.secret.len());
}
```

輸出：

```text
Config { name: "api", port: 8080, secret: "***" }
Config {
    name: "api",
    port: 8080,
    secret: "***",
}
密碼長度 6
```

### iter::once、iter::empty 與 Unicode 大小寫

`iter::once` 把單一值包成迭代器，常用來和其他迭代器 `chain` 在一起，例如在資料前面加一列標題；`iter::empty` 則是一個空的迭代器。`str::to_uppercase` 依 Unicode 規則轉大寫，像德文的 `ß` 會變成兩個字母 `SS`。

範例：

```rust
use std::iter;

fn main() {
    let header = iter::once("名稱");
    let rows = vec!["alpha", "beta"];
    let all: Vec<&str> = header.chain(rows).collect();
    println!("{:?}", all);

    let nothing: Vec<i32> = iter::empty().collect();
    println!("{:?}", nothing);

    println!("{}", "straße".to_uppercase());
}
```

輸出：

```text
["名稱", "alpha", "beta"]
[]
STRASSE
```

注意：Unicode 大小寫轉換可能改變字串長度，不要假設轉換前後的位元組數或字元數相同。

## 本版新增的棄用 API

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

| 模組 | 項目 | 官方說明 |
| --- | --- | --- |
| `std::mem` | [`min_align_of`](https://doc.rust-lang.org/std/mem/fn.min_align_of.html) | use align_of instead |
| `std::mem` | [`min_align_of_val`](https://doc.rust-lang.org/std/mem/fn.min_align_of_val.html) | use align_of_val instead |

## 修補版本

本版沒有修補版本。

## 已知漏洞

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

### 仍影響 `1.2.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-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-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-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.2 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-120-2015-08-07)
- [Rust 1.2 發布公告](https://blog.rust-lang.org/releases/1.2.0/)
- [rust-lang/rust 原始碼 1.2.0](https://github.com/rust-lang/rust/tree/1.2.0)
