# Rust 1.27

Rust 1.27 發布於 2018-06-21，目前最新修補版為 `1.27.2`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.27 引入 `dyn Trait` 語法：特徵物件從 `Box<Foo>` 改寫成 `Box<dyn Foo>`，一眼就能和一般結構、`impl Trait` 區分。同一版穩定了 x86／x86_64 的 SIMD 基礎設施 `std::arch`，`#[must_use]` 也能標在函式上，`Clone::clone`、`Iterator::collect` 等結果沒用到時會發出警告。官方文件站的所有書籍都可以搜尋，並新增說明編譯器用法的 The rustc Book。

### 語言變更

- 新增 `dyn Trait` 語法，與舊的裸特徵寫法等價，詳見 [特徵物件](/traits-objects)。
- `#[must_use]` 可以標在函式上，回傳值沒被使用時發出警告，詳見 [函式](/basics-functions)。
- 泛型參數（型別與生命週期）上可以加屬性；`proc` 不再是保留字。

### 標準庫重點

- SIMD 穩定：新增 `std::arch::x86`、`std::arch::x86_64`、`is_x86_feature_detected!` 巨集與 `#[target_feature(enable = "...")]` 屬性。
- 新增 `Option::filter`，詳見 [Option](/pkg-option)。
- 新增 `Iterator::try_fold`、`Iterator::try_for_each`，以及 `DoubleEndedIterator::rfind`、`rfold`、`try_rfold`，詳見 [std::iter](/pkg-iter)。
- 新增 `Duration::from_micros`、`from_nanos`、`subsec_micros`、`subsec_millis`，詳見 [std::time](/pkg-time)。
- 新增 `HashMap::remove_entry`、`String::replace_range`、`slice::rsplit`、`slice::swap_with_slice`、`hint::unreachable_unchecked`。
- `str::replace`、`Clone::clone`、`Iterator::collect`、`ToOwned::to_owned` 加上 `#[must_use]`。

### Cargo 與工具

- 新增 `--target-dir`，指定編譯產物的輸出目錄，詳見 [Cargo](/start-cargo)。
- `Cargo.toml` 新增 `autobins`、`autoexamples`、`autotests`、`autobenches`，控制是否自動偵測目標，詳見 [Cargo.toml](/modules-cargo)。
- `cargo metadata` 多輸出 `authors`、`categories`、`keywords`、`readme`、`repository` 與 `metadata` 表；Cargo 會快取編譯器資訊。

### 相容性注意

- 原子型別的 `Debug` 只印內部值，例如 `AtomicBool::new(true)` 印成 `true`。
- `repr(align(N))` 的上限改為 2²⁹。
- `Error::description()` 改為軟性棄用，實作 `Error` 時不必再提供，詳見 [自訂錯誤](/errors-custom)。
- 不能再直接從 core 呼叫 `CharExt`、`StrExt` 的方法。

### dyn Trait

以前 `Box<Foo>` 裡的 `Foo` 可能是結構，也可能是特徵，讀程式碼時要先查定義才知道。`dyn` 明確標示「這是特徵物件，透過 vtable 在執行期決定呼叫哪個實作」。需要在同一個集合放不同型別，或依條件回傳不同型別時，就用 `Box<dyn Trait>` 或 `&dyn Trait`。

範例：

```rust
trait Notifier {
    fn send(&self, msg: &str) -> String;
}

struct Email(&'static str);
struct Sms(u32);

impl Notifier for Email {
    fn send(&self, msg: &str) -> String {
        format!("寄信給 {}：{}", self.0, msg)
    }
}

impl Notifier for Sms {
    fn send(&self, msg: &str) -> String {
        format!("傳簡訊到 {}：{}", self.0, msg)
    }
}

fn broadcast(targets: &[Box<dyn Notifier>], msg: &str) {
    for t in targets {
        println!("{}", t.send(msg));
    }
}

fn pick(use_email: bool) -> Box<dyn Notifier> {
    if use_email {
        Box::new(Email("ops@example.com"))
    } else {
        Box::new(Sms(912345678))
    }
}

fn main() {
    let targets = vec![pick(true), pick(false)];
    broadcast(&targets, "伺服器重新啟動");

    let single: &dyn Notifier = &Sms(987654321);
    println!("{}", single.send("測試"));
}
```

輸出：

```text
寄信給 ops@example.com：伺服器重新啟動
傳簡訊到 912345678：伺服器重新啟動
傳簡訊到 987654321：測試
```

注意：1.27 當時省略 `dyn` 只是預設不警告的 lint；在較新的 edition 中省略 `dyn` 已是編譯錯誤，詳見 [Edition 演進](/evolution-editions)。

### Option::filter 與 Iterator::try_fold

`Option::filter` 在值存在且符合條件時保留 `Some`，否則變成 `None`。`try_fold` 像 `fold` 一樣累積結果，但閉包回傳 `Option` 或 `Result`，遇到 `None`／`Err` 就立刻停止；`try_for_each` 則是會提早停止的 `for_each`。

範例：

```rust
fn main() {
    let ages = [Some(20), Some(15), None];
    for age in ages {
        println!("{:?} -> {:?}", age, age.filter(|a| *a >= 18));
    }

    let nums = [100u8, 80, 90];
    let total = nums.iter().try_fold(0u8, |acc, &n| acc.checked_add(n));
    println!("u8 加總：{:?}", total);

    let small = [10u8, 20, 30];
    println!("u8 加總：{:?}", small.iter().try_fold(0u8, |acc, &n| acc.checked_add(n)));

    let r = ["1", "2", "x", "4"].iter().try_for_each(|s| {
        let n: i32 = s.parse().map_err(|_| format!("無法解析 {:?}", s))?;
        println!("處理 {}", n);
        Ok::<(), String>(())
    });
    println!("{:?}", r);

    println!("{:?}", [1, 2, 3, 4].iter().rfind(|&&x| x % 2 == 1));
}
```

輸出：

```text
Some(20) -> Some(20)
Some(15) -> None
None -> None
u8 加總：None
u8 加總：Some(60)
處理 1
處理 2
Err("無法解析 \"x\"")
Some(3)
```

注意：`100 + 80 + 90` 等於 270，超過 `u8` 上限 255，加到第三個數時 `checked_add` 回傳 `None`，`try_fold` 就此停止；`"4"` 也因為前面的錯誤而沒有被處理。

## 本版新增的棄用 API

本版沒有新增棄用 API。

## 修補版本

| 版本 | 發布日期 | 含安全修補 | 內容（官方原文） |
| --- | --- | --- | --- |
| `1.27.1` | 2018-07-10 | 是 | rustdoc would execute plugins in the /tmp/rustdoc/plugins directory when running, which enabled executing code as some other user on a given machine. This release fixes that vulnerability; you can read more about this on the blog. The associated CVE is [CVE-2018-1000622]. Thank you to Red Hat for responsibly disclosing this vulnerability to us.；The borrow checker was fixed to avoid an additional potential unsoundness when using match ergonomics: #51415, #49534. |
| `1.27.2` | 2018-07-20 | 否 | The borrow checker was fixed to avoid potential unsoundness when using match ergonomics: #52213. |

## 已知漏洞

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

### 本版已修正

| 編號 | 元件 | 摘要（官方原文） | 影響範圍 | 修正於 |
| --- | --- | --- | --- | --- |
| [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) |

### 仍影響 `1.27.2`

| 編號 | 元件 | 摘要（官方原文） | 影響範圍 | 修正於 |
| --- | --- | --- | --- | --- |
| [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-2020-36317](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-36317) | std | String::retain allows safely creating invalid strings when abusing panic | 1.26.0 起，早於 1.49.0 | [1.49.0](/rust-1-49) |
| [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-2018-1000810](https://groups.google.com/forum/#!topic/rustlang-security-announcements/CmSuTm-SaU0) | std | Buffer overflow vulnerability in str::repeat() | 1.26.0 起，早於 1.29.1 | [1.29.1](/rust-1-29) |
| [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-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.27 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1270-2018-06-21)
- [Rust 1.27 發布公告](https://blog.rust-lang.org/releases/1.27.0/)
- [rust-lang/rust 原始碼 1.27.0](https://github.com/rust-lang/rust/tree/1.27.0)
