# Rust 1.39

Rust 1.39 發布於 2019-11-07，目前最新修補版為 `1.39.0`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.39 正式推出 `async fn`、`async` 區塊與 `.await`，非同步程式可以寫得像同步程式一樣直觀，是 Rust 發展中的重要里程碑。標準庫只提供 `Future` 等基礎型別，實際執行非同步任務需要搭配執行器（executor），通常由第三方 crate 提供。升級時要注意：舊借用檢查器接受、但 NLL 拒絕的程式碼，在 2018 edition 從警告變成錯誤；`try!` 巨集也開始產生棄用警告，請改用 `?`。

### 語言變更

- 可以用 `async fn`、`async {}`、`async move {}` 建立非同步函式與區塊，並在其中以 `.await` 等待結果，詳見 [async 基礎](/async-basics)。
- 函式、閉包與函式指標的參數可以加上 `cfg`、`cfg_attr`、`allow`、`warn`、`deny`、`forbid` 等屬性。
- `match` 的 `if` 守衛中，可以對以移動方式綁定的變數取共用參考，詳見 [match](/control-match)。

### 標準庫重點

- `Vec::new`、`String::new`、`LinkedList::new` 改為 `const fn`，可以用在 `const` 與 `static` 中，詳見 [Vec](/pkg-vec)。
- `str::len`、`[T]::len`、`str::as_bytes` 以及 `abs`、`wrapping_abs`、`overflowing_abs` 改為 `const fn`。
- `Pin::into_inner` 穩定，詳見 [std::pin](/pkg-pin)。
- `Instant::checked_duration_since` 與 `Instant::saturating_duration_since` 穩定，詳見 [std::time](/pkg-time)。

### Cargo 與工具

- git 相依只要同時指定 `version` 就能發佈。
- `--all` 更名為 `--workspace`，`--all` 已棄用，詳見 [工作區](/modules-workspaces)。
- 測試執行檔可以傳入 `--show-output`，印出通過的測試的輸出。
- 編譯器的錯誤訊息會裁切程式碼片段以符合終端機寬度。

### 相容性注意

- 2018 edition 中，舊借用檢查器接受但 NLL 拒絕的程式碼改為錯誤；2015 edition 會在 1.40 跟進。
- `rustdoc` 執行文件測試時需要 `rustc` 安裝在同一個目錄。
- `asinh(-0.0)` 改為正確回傳 `-0.0`。

### async 與 .await

`async fn` 呼叫後不會立刻執行，而是回傳一個 `Future`，代表「之後會算出的值」；在另一個 `async` 函式裡用 `.await` 等待它完成。範例中 `compute()` 被呼叫時只建立了 `Future`，所以先印出「尚未執行」，交給 `block_on` 輪詢（poll）後才真正計算出 `26`。

這裡的 `block_on` 是教學用的最小執行器，用到 Rust 1.68 起的 `pin!` 與 1.85 起的 `Waker::noop()`，不斷輪詢直到完成；實際專案會使用第三方 crate 提供的執行器，它們能在等待 I/O 時讓出執行緒。

範例：

```rust
use std::future::Future;
use std::pin::pin;
use std::task::{Context, Poll, Waker};

async fn add(a: i32, b: i32) -> i32 {
    a + b
}

async fn compute() -> i32 {
    let x = add(1, 2).await;
    let y = add(x, 10).await;
    y * 2
}

fn block_on<F: Future>(fut: F) -> F::Output {
    let mut fut = pin!(fut);
    let mut cx = Context::from_waker(Waker::noop());
    loop {
        if let Poll::Ready(v) = fut.as_mut().poll(&mut cx) {
            return v;
        }
    }
}

fn main() {
    let fut = compute();
    println!("尚未執行");
    println!("{}", block_on(fut));
}
```

輸出：

```text
尚未執行
26
```

注意：`Future` 是惰性的，建立後如果沒有被 `.await` 或交給執行器，裡面的程式碼永遠不會執行。

### 在 match 守衛中借用移動綁定

`match data` 會把 `Box` 移動到分支的 `nums`。以前在 `if` 守衛裡呼叫 `nums.iter()`（需要借用）會被拒絕；現在守衛可以先借用檢查條件，進入分支後再取得所有權，例如把 `Box` 解開成 `Vec`。

範例：

```rust
fn main() {
    let data: Box<Vec<i32>> = Box::new(vec![1, 2, 3, 4]);
    match data {
        nums if nums.iter().sum::<i32>() == 10 => {
            let owned: Vec<i32> = *nums;
            println!("總和是 10：{:?}", owned);
        }
        _ => println!("其他"),
    }
}
```

輸出：

```text
總和是 10：[1, 2, 3, 4]
```

## 本版新增的棄用 API

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

| 模組 | 項目 | 官方說明 |
| --- | --- | --- |
| `std` | [`try!`](https://doc.rust-lang.org/std/macro.try.html) | use the ? operator instead |
| `std::mem` | [`uninitialized`](https://doc.rust-lang.org/std/mem/fn.uninitialized.html) | use mem::MaybeUninit instead |

## 修補版本

本版沒有修補版本。

## 已知漏洞

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

### 仍影響 `1.39.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-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-36323](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-36323) | std | API soundness issue in join() implementation of \[Borrow\<str\>\] | 1.28.0 起，早於 1.52.0 | [1.52.0](/rust-1-52) |
| [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) |

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

## 資料來源

- [Rust 1.39 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1390-2019-11-07)
- [Rust 1.39 發布公告](https://blog.rust-lang.org/releases/1.39.0/)
- [rust-lang/rust 原始碼 1.39.0](https://github.com/rust-lang/rust/tree/1.39.0)
