Rust 1.57

最後更新


Rust 1.57 發布於 2021-12-02,目前最新修補版為 1.57.0,已停止支援,請升級到 1.100.1。

版本介紹


Rust 1.57 讓 panic! 可以在 const 情境中使用,搭配 assert! 就能寫出編譯期檢查;Cargo 支援自訂名稱的 profile;Vec、String、HashMap 等集合新增可失敗的配置 API try_reserve。對新手來說,編譯期斷言能把錯誤提早到 cargo build 時發現。升級時要注意:衍生(derive)的 Clone 與 Debug 實作不再算是「使用」欄位,開了 #![deny(dead_code)] 的專案可能編譯失敗。

語言變更


  • const 情境中可以呼叫 panic! 與 assert!,詳見 常數。
  • 巨集屬性可以寫在 #[derive] 之後,並看到 cfg 處理前的原始輸入,詳見 程序式巨集。
  • 大括號形式的巨集呼叫可以出現在運算式中,例如 m!{ .. }.method() 與 m!{ .. }?。
  • 死碼分析忽略衍生的 Clone 與 Debug 實作。

標準庫重點


  • Vec、String、VecDeque 新增 try_reserve、try_reserve_exact,HashMap、HashSet 新增 try_reserve,錯誤型別為 collections::TryReserveError,詳見 集合。
  • 新增 Iterator::map_while,詳見 std::iter。
  • 新增 [T; N]::as_slice、[T; N]::as_mut_slice,詳見 陣列。
  • 新增 Command::get_program、get_args、get_envs、get_current_dir,詳見 std::process。
  • 更多函式標上 #[must_use],忽略回傳值時會警告;Unicode 更新到 14.0。

Cargo 與工具


  • 支援自訂 profile,例如 [profile.production] 搭配 inherits = "release",用 --profile production 建置,輸出到 target/production,詳見 Cargo。

相容性注意


  • 死碼分析忽略衍生的 Clone 與 Debug,設定 #![deny(dead_code)] 的專案可能因此編譯失敗。

const 中的 panic! 與編譯期斷言


const fn 裡可以呼叫 panic!,在 const 項目中用 assert! 檢查條件。如果常數求值時真的觸發 panic,就是編譯錯誤,程式根本不會產出。
範例:
  1. const fn checked_percent(value: u32) -> u32 {
  2. if value > 100 {
  3. panic!("percent must be <= 100");
  4. }
  5. value
  6. }
  7. const HALF: u32 = checked_percent(50);
  8. const _: () = assert!(std::mem::size_of::<u64>() == 8);
  9. fn main() {
  10. println!("{HALF}");
  11. }

輸出:
  1. 50

把常數改成 checked_percent(150) 時,這段無法編譯:
  1. const TOO_MUCH: u32 = checked_percent(150);
  2. const fn checked_percent(value: u32) -> u32 {
  3. if value > 100 {
  4. panic!("percent must be <= 100");
  5. }
  6. value
  7. }
  8. fn main() {
  9. println!("{TOO_MUCH}");
  10. }

輸出:
  1. error[E0080]: evaluation panicked: percent must be <= 100
  2. --> main.rs:1:23
  3. |
  4. 1 | const TOO_MUCH: u32 = checked_percent(150);
  5. | ^^^^^^^^^^^^^^^^^^^^ evaluation of `TOO_MUCH` failed inside this call

注意:這版的 const 中 panic! 只接受靜態字串,或單一個以 {} 插入的 &str 值,還不支援完整的格式化功能。

try_reserve


一般的 reserve 在配置記憶體失敗時會中止整個程式;try_reserve 改為回傳 Result,失敗時得到 TryReserveError,集合本身仍然可用。
範例:
  1. fn main() {
  2. let mut buf: Vec<u8> = Vec::new();
  3. match buf.try_reserve(1024) {
  4. Ok(()) => println!("reserved: {}", buf.capacity() >= 1024),
  5. Err(e) => println!("failed: {e}"),
  6. }
  7. let mut s = String::new();
  8. match s.try_reserve(usize::MAX) {
  9. Ok(()) => println!("unexpected"),
  10. Err(e) => println!("failed: {e}"),
  11. }
  12. s.push_str("still usable");
  13. println!("{s}");
  14. }

輸出:
  1. reserved: true
  2. failed: memory allocation failed because the computed capacity exceeded the collection's maximum
  3. still usable

注意:try_reserve 回傳成功不代表作業系統真的給了記憶體,例如 Linux 開啟 overcommit 時,實際使用時仍可能拿不到。

Iterator::map_while


map_while(f) 對每個元素呼叫 f,只要回傳 Some 就繼續並取出內容,第一次回傳 None 就停止。下面在遇到第一個無法解析的字串時結束,後面的 "15" 不會被處理。
範例:
  1. fn main() {
  2. let input = ["4", "8", "x", "15"];
  3. let numbers: Vec<i32> = input.iter().map_while(|s| s.parse().ok()).collect();
  4. println!("{:?}", numbers);
  5. }

輸出:
  1. [4, 8]

本版新增的棄用 API


本版沒有新增棄用 API。

修補版本


本版沒有修補版本。

已知漏洞


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

仍影響 1.57.0


編號元件摘要(官方原文)影響範圍修正於
CVE-2026-5222cargoCargo can be coerced to share credentials between registries早於 1.96.01.96.0
CVE-2026-5223cargoCrates in third party registries can override the cached source of other crates早於 1.96.01.96.0
CVE-2024-43402stdstd::process::Command batch files argument escaping could be bypassed with trailing whitespace or periods早於 1.81.01.81.0
CVE-2024-24576stdstd::process::Command did not properly escape arguments of batch files on Windows早於 1.77.21.77.2
CVE-2023-38497cargoCargo not respecting umask when extracting crate archives早於 1.71.11.71.1
CVE-2022-46176cargoCargo did not verify SSH host keys早於 1.66.11.66.1
CVE-2022-36113cargoExtracting malicious crates can corrupt arbitrary files早於 1.64.01.64.0
CVE-2022-36114cargoExtracting malicious crates can fill the file system早於 1.64.01.64.0
CVE-2022-21658stdRace condition in std::fs::remove_dir_all早於 1.58.11.58.1

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

資料來源