# Rust 1.6

Rust 1.6 發布於 2016-01-21，目前最新修補版為 `1.6.0`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.6 穩定了核心函式庫 libcore：加上 `#![no_std]` 屬性的 crate 只連結不依賴任何平台的 core，不連結完整標準庫，作業系統與嵌入式開發因此能在穩定版上起步。標準庫穩定約 30 個 API，包括各集合的 `drain`、取代 `push_all` 的 `Vec::extend_from_slice`，以及整數轉浮點數的無損 `From` 轉換。升級要注意：crates.io 拒絕發布含萬用字元（`*`）版本相依的 crate，必須寫明版本範圍。

### 語言變更

- `#![no_std]` 讓 crate 不連結標準庫，只連結 core library；core 定義常用的型別與特徵，大部分 API 已穩定。
- 解析器遇到容易混淆的相似 Unicode 字元時會指出可能的原因。
- 部分巨集錯誤改在定義時就回報，而不是等到展開時，詳見 [宣告式巨集](/macros-declarative)。

### 標準庫重點

- `Vec`、`String`、`VecDeque`、`HashMap`、`HashSet`、`BinaryHeap` 新增 `drain`，移出元素同時保留原本的記憶體配置，詳見 [std::collections](/pkg-collections)。
- `Vec::extend_from_slice`（原名 `push_all`）穩定，比一般的 `extend` 快得多，詳見 [Vec](/pkg-vec)。
- `Read::read_exact` 讀滿指定長度的緩衝區，`ErrorKind::UnexpectedEof`（原名 `UnexpectedEOF`）穩定，詳見 [std::io](/pkg-io)。
- `fs::DirBuilder` 可設定 `recursive` 一次建立多層目錄，詳見 [std::fs](/pkg-fs)。
- `Mutex` 與 `RwLock` 新增 `get_mut`、`into_inner`，詳見 [std::sync](/pkg-sync)。
- `Iterator::min_by_key`、`max_by_key`（原名 `min_by`、`max_by`）穩定，詳見 [std::iter](/pkg-iter)。
- 整數轉浮點數在不損失精度時實作 `From`（32 位元整數轉 `f32`、64 位元整數轉浮點數、`isize`／`usize` 不在此列），`f32` 轉 `f64` 也實作 `From`，詳見 [型別轉換](/types-conversion)。
- `Box<T>`、`Rc<T>`、`Arc<T>` 實作 `From<T>`；`&Path`、`&PathBuf` 實作 `IntoIterator`。
- `assert_eq!` 接受陣列這類未實作 `Sized` 的引數，詳見 [單元測試](/testing-unit)。

### Cargo 與工具

- crates.io 拒絕發布含萬用字元相依的 crate，版本要寫成 `^`、`~` 或 `=` 等形式，詳見 [Cargo](/modules-cargo)。
- 建置腳本可以輸出 `rerun-if-changed`，指定哪些檔案變動時才重新執行。
- Cargo 預設會到 `$CARGO_HOME/bin` 尋找子命令；`cargo clean` 接受 `--release`。
- `unreachable_code` lint 在函式呼叫的引數發散（diverge）時發出警告。

### 相容性注意

- 編譯器不再使用 `RUST_PATH` 環境變數尋找 crate。
- 隱私檢查器修正多個 bug，部分原本能編譯的程式碼會失敗。
- 模組與單元／元組結構不能同名。
- 不能再用元組結構模式 `Foo(..)` 比對單元結構（目前為警告），與常數同名的模式改為錯誤，詳見 [模式](/control-patterns)。

### drain 移出部分元素

`drain(範圍)` 把指定範圍的元素「搬出來」交給迭代器，原集合只留下剩下的部分。`String::drain` 的範圍以位元組計算；`extend_from_slice` 則把一段切片複製到 `Vec` 尾端。

範例：

```rust
fn main() {
    let mut queue = vec!["a", "b", "c", "d", "e"];
    let batch: Vec<&str> = queue.drain(..2).collect();
    println!("取出 {:?}，剩下 {:?}", batch, queue);

    let mut s = String::from("Hello, Rust!");
    let greeting: String = s.drain(..7).collect();
    println!("{:?} / {:?}", greeting, s);

    let mut all = vec![0; 2];
    all.extend_from_slice(&[7, 8, 9]);
    println!("{:?}", all);
}
```

輸出：

```text
取出 ["a", "b"]，剩下 ["c", "d", "e"]
"Hello, " / "Rust!"
[0, 0, 7, 8, 9]
```

注意：`String::drain` 的範圍端點必須落在字元邊界上，否則會 panic。

### 無損數值轉換 From

`From` 只實作在「一定不會損失資訊」的轉換上，例如 `u8` 轉 `u32`、`u32` 轉 `f64`、`f32` 轉 `f64`。可能遺失精度的 `i64` 轉 `f64` 沒有 `From`，必須明確使用 `as`，讓讀程式的人知道這裡有風險。

範例：

```rust
fn average(values: &[i32]) -> f64 {
    let sum: i32 = values.iter().sum();
    f64::from(sum) / f64::from(values.len() as u32)
}

fn main() {
    let small: u8 = 200;
    let wider: u32 = small.into();
    let as_float = f64::from(wider);
    println!("{} {} {}", small, wider, as_float);

    let half = f64::from(1.5f32);
    println!("{}", half);

    println!("{}", average(&[3, 4, 8]));
}
```

輸出：

```text
200 200 200
1.5
5
```

### min_by_key 與 max_by_key

依照某個「鍵」找出最小或最大的元素，不必自己寫比較函式。迭代器為空時回傳 `None`。

範例：

```rust
fn main() {
    let words = ["banana", "fig", "cherry", "kiwi"];
    println!("{:?}", words.iter().min_by_key(|w| w.len()));
    println!("{:?}", words.iter().max_by_key(|w| w.len()));

    let empty: [&str; 0] = [];
    println!("{:?}", empty.iter().min_by_key(|w| w.len()));
}
```

輸出：

```text
Some("fig")
Some("cherry")
None
```

注意：有多個元素同時是最大值時，`max_by_key` 回傳最後一個，`min_by_key` 回傳第一個；上例 `banana` 與 `cherry` 一樣長，結果是 `cherry`。

## 本版新增的棄用 API

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

| 模組 | 項目 | 官方說明 |
| --- | --- | --- |
| `std::sync` | [`Condvar::wait_timeout_ms`](https://doc.rust-lang.org/std/sync/struct.Condvar.html#method.wait_timeout_ms) | replaced by std::sync::Condvar::wait_timeout |
| `std::sync::poison` | [`Condvar::wait_timeout_ms`](https://doc.rust-lang.org/std/sync/poison/struct.Condvar.html#method.wait_timeout_ms) | replaced by std::sync::Condvar::wait_timeout |
| `std::thread` | [`park_timeout_ms`](https://doc.rust-lang.org/std/thread/fn.park_timeout_ms.html) | replaced by std::thread::park_timeout |
| `std::thread` | [`sleep_ms`](https://doc.rust-lang.org/std/thread/fn.sleep_ms.html) | replaced by std::thread::sleep |

## 修補版本

本版沒有修補版本。

## 已知漏洞

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

### 仍影響 `1.6.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-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.6 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-160-2016-01-21)
- [Rust 1.6 發布公告](https://blog.rust-lang.org/releases/1.6.0/)
- [rust-lang/rust 原始碼 1.6.0](https://github.com/rust-lang/rust/tree/1.6.0)
