Rust 1.80
最後更新
Rust 1.80 發布於 2024-07-25,目前最新修補版為
1.80.1,已停止支援,請升級到 1.100.1。版本介紹
Rust 1.80 把
LazyCell 與 LazyLock 納入標準庫:延遲到第一次存取才初始化的值,從此不必再依賴 lazy_static 或 once_cell crate。對新手來說,宣告「第一次用到才建立」的全域設定或查表變得很簡單;模式比對也終於可以寫排除端點的區間 a..b。升級時要注意:Cargo 預設檢查所有 cfg 名稱與值,拼錯的 feature 會出現 unexpected_cfgs 警告;Box<str> 新增的 FromIterator 實作讓部分型別推斷失敗,time crate 需升級到 0.3.35 以上。語言變更
- 模式中可以使用排除端點的區間
a..b與..b,詳見 match。 - 保證
Result在部分情況下的記憶體布局與 ABI。 - 官方文件明確記錄最大配置大小。
標準庫重點
- 新增
LazyCell與LazyLock,詳見 std::cell 與 std::sync。 size_of、size_of_val、align_of、align_of_val加入 prelude,不必再寫mem::,詳見 prelude。- 新增
Option::take_if,條件成立時才取出值,詳見 Option。 - 切片與
str新增split_at_checked,越界時回傳None而不是 panic,詳見 切片。 str與[u8]新增trim_ascii、trim_ascii_start、trim_ascii_end,詳見 str。Box<[T]>實作IntoIterator;Vec<[T; N]>新增into_flattened,[[T; N]]新增as_flattened。- 新增
Duration::div_duration_f64、Seek::seek_relative、Ipv4Addr::to_bits等。
Cargo 與工具
- 預設啟用
cfg名稱與值檢查,未知的cfg以unexpected_cfgslint 警告,可在[lints]表設定額外的合法值,詳見 Cargo 與套件。 cargo update --precise可以指定已被撤回(yanked)的版本。
相容性注意
std::env::set_var、remove_var不再能轉成安全的函式指標。std::io::StdoutLock與StderrLock不再是Sync。Box<str>新增FromIterator實作,部分程式的型別推斷會失敗,timecrate 0.3.35 以前的版本受影響。- rustfmt 對非 ASCII 字元的行長估算方式改變。
LazyLock:第一次存取才初始化
LazyLock 在建立時就記住初始化函式,第一次被讀取時才執行一次,之後都回傳同一個值;它是執行緒安全的,可以放在 static。不需要跨執行緒時用 LazyCell,它沒有同步成本,但不能放在一般的 static。範例:
- use std::collections::BTreeMap;
- use std::sync::LazyLock;
- static COLORS: LazyLock<BTreeMap<&str, u32>> = LazyLock::new(|| {
- println!("初始化色票");
- BTreeMap::from([("red", 0xff0000), ("green", 0x00ff00), ("blue", 0x0000ff)])
- });
- fn main() {
- println!("程式開始");
- println!("{:06x}", COLORS["green"]);
- println!("{:06x}", COLORS["blue"]);
- println!("共 {} 種", COLORS.len());
- }
輸出:
- 程式開始
- 初始化色票
- 00ff00
- 0000ff
- 共 3 種
模式中的排除區間
以前模式只能寫
a..=b 或 a..,相鄰的區間要自己減一;現在可以寫 0..60、60..80,上一段的結尾直接當下一段的開頭。編譯器的窮舉檢查會指出區間之間的縫隙。範例:
- fn grade(score: u32) -> &'static str {
- match score {
- 0..60 => "不及格",
- 60..80 => "及格",
- 80..100 => "優秀",
- 100.. => "滿分",
- }
- }
- fn main() {
- for s in [59, 60, 79, 80, 100] {
- println!("{s}: {}", grade(s));
- }
- }
輸出:
- 59: 不及格
- 60: 及格
- 79: 及格
- 80: 優秀
- 100: 滿分
本版新增的棄用 API
本版沒有新增棄用 API。
修補版本
| 版本 | 發布日期 | 含安全修補 | 內容(官方原文) |
|---|---|---|---|
1.80.1 | 2024-08-08 | 否 | Fix miscompilation in the jump threading MIR optimization when comparing floats;Revert changes to the dead_code lint from 1.80.0 |
已知漏洞
影響
1.80.0 的已知漏洞共 3 個;在本版修正的共 0 個;仍影響最新修補版 1.80.1 的共 3 個。官方未公布影響範圍的漏洞只列在修正它的版本,不計入其他版本。仍影響 1.80.1
| 編號 | 元件 | 摘要(官方原文) | 影響範圍 | 修正於 |
|---|---|---|---|---|
| CVE-2026-5222 | cargo | Cargo can be coerced to share credentials between registries | 早於 1.96.0 | 1.96.0 |
| CVE-2026-5223 | cargo | Crates in third party registries can override the cached source of other crates | 早於 1.96.0 | 1.96.0 |
| CVE-2024-43402 | std | std::process::Command batch files argument escaping could be bypassed with trailing whitespace or periods | 早於 1.81.0 | 1.81.0 |
本版已停止支援,不會再修正這些漏洞;請升級到
1.100.1。