# Rust 1.63

Rust 1.63 發布於 2022-08-11，目前最新修補版為 `1.63.0`，**已停止支援**，請升級到 `1.100.1`。

## 版本介紹

Rust 1.63 最重要的新功能是作用域執行緒（scoped threads）：`std::thread::scope` 保證裡面開的執行緒在函式返回前全部結束，所以執行緒可以直接借用區域變數，不必再把資料包進 `Arc`。`Mutex::new`、`RwLock::new`、`Condvar::new` 也能在 `const` 環境呼叫，全域的 `static Mutex` 不再需要 `lazy_static`。這一版還完成了非詞法生命週期（NLL）的遷移，舊的借用檢查器從所有 edition 移除，對既有程式的行為沒有影響。

### 語言變更

- 舊的詞法借用檢查器完全移除，所有 edition 都使用 NLL 借用檢查器，觀念見 [生命週期](/ownership-lifetimes)。
- 函式參數有 `impl Trait` 時，其他泛型參數也可以用 turbofish（`foo::<u32>(...)`）明確指定；`impl Trait` 本身仍不能指定，泛型見 [泛型](/generics-basics)。
- 移除標籤與生命週期遮蔽（shadowing）的警告。

### 標準庫重點

- `thread::scope`、`thread::Scope`、`thread::ScopedJoinHandle` 穩定，詳見 [std::thread](/pkg-thread) 與 [執行緒](/concurrency-threads)。
- `Mutex::new`、`RwLock::new`、`Condvar::new` 可在 const 環境使用，詳見 [std::sync](/pkg-sync)。
- `array::from_fn` 依索引產生陣列的每個元素，詳見 [陣列](/pkg-array)。
- `Path::try_exists` 在無法判斷路徑是否存在時回傳錯誤，而不是靜默回傳 `false`，詳見 [std::path](/pkg-path)。
- I/O 安全（I/O safety）型別穩定：Unix 的 `OwnedFd`、`BorrowedFd`、`AsFd`，Windows 的 `OwnedHandle`、`BorrowedHandle`、`OwnedSocket` 等，用型別區分「擁有」與「借用」檔案描述子。
- `Box::into_pin`、`ToOwned::clone_into`、`Ref::filter_map`、`RefMut::filter_map`、`Ipv6Addr::to_ipv4_mapped` 一併穩定；`str::from_utf8` 可在 const 環境使用。
- `VecDeque<u8>` 實作 `Read` 與 `Write`。

### Cargo 與工具

- `--config path` 命令列參數穩定，可指定額外的設定檔。
- `Cargo.toml` 的 `rust-version` 會以環境變數 `CARGO_PKG_RUST_VERSION` 提供給編譯中的程式，Cargo 見 [Cargo](/modules-cargo)。

### 相容性注意

- 浮點數轉 `Duration` 改用四捨五入，結果可能與舊版有些微差異，詳見 [std::time](/pkg-time)。
- `#[link]` 屬性檢查更嚴格，以前被忽略的無效參數會變成錯誤。

### thread::scope：可以借用區域變數的執行緒

`thread::spawn` 要求閉包是 `'static`，因為執行緒可能比當前函式活得更久。`thread::scope` 會在區塊結束前自動 join 所有執行緒，編譯器因此知道借用是安全的：多個執行緒可以同時讀 `words` 的切片，也能讓單一執行緒可變借用 `total`。區塊的回傳值會成為 `scope` 的回傳值。

範例：

```rust
use std::thread;

fn main() {
    let words = vec!["apple", "banana", "cherry", "date"];
    let mut total = 0;

    let (left, right) = words.split_at(2);
    let (a, b) = thread::scope(|s| {
        let h1 = s.spawn(|| left.iter().map(|w| w.len()).sum::<usize>());
        let h2 = s.spawn(|| right.iter().map(|w| w.len()).sum::<usize>());
        (h1.join().unwrap(), h2.join().unwrap())
    });

    thread::scope(|s| {
        s.spawn(|| total = a + b);
    });

    println!("{a} {b} {total}");
    println!("{words:?}");
}
```

輸出：

```text
11 10 21
["apple", "banana", "cherry", "date"]
```

注意：同一時間若有兩個執行緒都要可變借用同一個變數，仍會被借用檢查器拒絕；作用域只解決「活得夠久」的問題，不解決資料競爭。

### const Mutex::new：免套件的全域鎖

`Mutex::new` 變成 `const fn` 後，可以直接寫在 `static` 的初始值裡，所有執行緒共用同一把鎖保護的資料。輸出前先排序，避免執行緒交錯造成順序不固定。

範例：

```rust
use std::sync::Mutex;
use std::thread;

static LOG: Mutex<Vec<String>> = Mutex::new(Vec::new());

fn record(msg: &str) {
    LOG.lock().unwrap().push(msg.to_string());
}

fn main() {
    thread::scope(|s| {
        for i in 0..3 {
            s.spawn(move || record(&format!("worker {i}")));
        }
    });
    let mut log = LOG.lock().unwrap();
    log.sort();
    println!("{log:?}");
}
```

輸出：

```text
["worker 0", "worker 1", "worker 2"]
```

### array::from_fn：依索引產生陣列

`std::array::from_fn` 接受一個以索引 `usize` 為參數的閉包，呼叫 N 次組成 `[T; N]`。長度由型別標註決定，元素不必實作 `Copy` 或 `Default`，所以也能建立 `[String; 3]`。

範例：

```rust
fn main() {
    let squares: [u32; 5] = std::array::from_fn(|i| (i as u32 + 1).pow(2));
    println!("{squares:?}");

    let labels: [String; 3] = std::array::from_fn(|i| format!("item-{i}"));
    println!("{labels:?}");
}
```

輸出：

```text
[1, 4, 9, 16, 25]
["item-0", "item-1", "item-2"]
```

## 本版新增的棄用 API

本版沒有新增棄用 API。

## 修補版本

本版沒有修補版本。

## 已知漏洞

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

### 仍影響 `1.63.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) |
| [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) |

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

## 資料來源

- [Rust 1.63 Release Notes](https://doc.rust-lang.org/stable/releases.html#version-1630-2022-08-11)
- [Rust 1.63 發布公告](https://blog.rust-lang.org/releases/1.63.0/)
- [rust-lang/rust 原始碼 1.63.0](https://github.com/rust-lang/rust/tree/1.63.0)
