# Rust 1.64

Rust 1.64 發布於 2022-09-22，目前最新修補版為 `1.64.0`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.64 穩定了 `IntoFuture`：`.await` 不只能等待 `Future`，也能等待任何可以轉成 `Future` 的型別，讓建構器（builder）風格的 API 少寫一個 `.send()`。C 互通用的 `c_int`、`CStr` 等型別也放進了 `core::ffi` 與 `alloc::ffi`，沒有 `std` 的環境也能使用。rust-analyzer 改由 rustup 提供，Cargo 則支援工作區繼承設定。升級要注意：Linux 目標的最低需求提高到 kernel 3.2 與 glibc 2.17，網路位址型別的記憶體布局也改變了。

### 語言變更

- union 可以包含可變參考，或由允許型別組成的元組。
- 新增預設允許的 `unused_tuple_struct_fields` lint，未來會改為預設警告。

### 標準庫重點

- `future::IntoFuture`、`future::poll_fn` 與 `task::ready!` 穩定，非同步觀念見 [async 基礎](/async-basics) 與 [std::future](/pkg-future)。
- `c_char`、`c_int`、`c_ulong` 等型別別名可從 `core::ffi` 與 `std::ffi` 取得；`CStr` 進入 `core::ffi`，`CString` 進入 `alloc::ffi`，詳見 [std::ffi](/pkg-ffi)。
- `NonZero*` 新增 `checked_mul`、`saturating_add`、`abs` 等運算方法，詳見 [std::num](/pkg-num)。
- `OsString` 實作 `fmt::Write`，可以用 `write!` 寫入。
- Unix 的 `CommandExt::process_group` 穩定，詳見 [std::process](/pkg-process)。
- `slice::from_raw_parts` 可在 const 環境使用。

### Cargo 與工具

- 工作區成員可以從 `[workspace.package]` 與 `[workspace.dependencies]` 繼承版本、相依等共用設定，詳見 [工作區](/modules-workspaces)。
- `cargo build` 可以重複傳入多個 `--target`，一次建置多個目標；`build.target` 設定也接受陣列。
- `--jobs` 接受負數，代表「CPU 數減去該值」；`cargo add` 會一併更新 `Cargo.lock`。
- `rust-analyzer` 成為 stable 通道的 rustup 元件：`rustup component add rust-analyzer`，工具總覽見 [開發工具](/modules-tools)。

### 相容性注意

- `-linux-gnu` 目標最低需要 Linux kernel 3.2 與 glibc 2.17。
- `Ipv4Addr`、`Ipv6Addr`、`SocketAddrV4`、`SocketAddrV6` 改用更精簡的 Rust 布局；用 `transmute` 依賴舊布局的程式會出錯，詳見 [std::net](/pkg-net)。
- 這是最後一個附帶 RLS 的版本，1.65 起改由 rust-analyzer 取代。
- `BTreeMap` 修正一個可能讓借用資料在容器之前被 drop 的健全性（soundness）錯誤。

### IntoFuture：讓建構器可以直接 .await

`IntoFuture` 之於 `.await`，就像 `IntoIterator` 之於 `for` 迴圈：`x.await` 會先呼叫 `x.into_future()`。下面的 `Request` 是一個建構器，實作 `IntoFuture` 後，設定完選項就能直接 `.await`，不必另外呼叫 `.send()`。

範例中的 `block_on` 是為了在沒有非同步執行環境套件時也能執行；它借用了之後版本才穩定的 `pin!`（1.68）與 `Waker::noop`（1.85）。

範例：

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

struct Request {
    path: String,
    retries: u32,
}

impl Request {
    fn new(path: &str) -> Self {
        Request { path: path.to_string(), retries: 0 }
    }

    fn retries(mut self, n: u32) -> Self {
        self.retries = n;
        self
    }
}

impl IntoFuture for Request {
    type Output = String;
    type IntoFuture = Ready<String>;

    fn into_future(self) -> Self::IntoFuture {
        ready(format!("GET {} (retries={})", self.path, self.retries))
    }
}

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 out = block_on(async { Request::new("/users").retries(2).await });
    println!("{out}");
}
```

輸出：

```text
GET /users (retries=2)
```

### OsString 支援 write!

`OsString` 用來存放作業系統的字串（檔名、環境變數），不保證是 UTF-8。從這版起它實作 `fmt::Write`，可以像 `String` 一樣用 `write!` 組字串，不必先轉成 `String` 再轉回來。

範例：

```rust
use std::ffi::OsString;
use std::fmt::Write;

fn main() {
    let mut name = OsString::from("report");
    write!(name, "-{}.txt", 2024).unwrap();
    println!("{name:?}");
}
```

輸出：

```text
"report-2024.txt"
```

## 本版新增的棄用 API

本版沒有新增棄用 API。

## 修補版本

本版沒有修補版本。

## 已知漏洞

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

### 仍影響 `1.64.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-40030](https://github.com/rust-lang/cargo/security/advisories/GHSA-wrrj-h57r-vx9p) | cargo | Malicious dependencies can inject arbitrary JavaScript into cargo-generated timing reports | 1.60.0 起，早於 1.72.0 | [1.72.0](/rust-1-72) |
| [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) |

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

## 資料來源

- [Rust 1.64 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1640-2022-09-22)
- [Rust 1.64 發布公告](https://blog.rust-lang.org/releases/1.64.0/)
- [rust-lang/rust 原始碼 1.64.0](https://github.com/rust-lang/rust/tree/1.64.0)
