Rust 1.65

最後更新


Rust 1.65 發布於 2022-11-03,目前最新修補版為 1.65.0,已停止支援,請升級到 1.100.1。

版本介紹


Rust 1.65 是語言功能很豐富的一版:泛型關聯型別(generic associated types,GATs)、let-else 與「從具名區塊 break」同時穩定。let-else 對新手最有感,它讓「取出值,取不到就提早返回」寫成兩三行,不必再巢狀 match。標準庫則加入 std::backtrace::Backtrace,可以在任何時候擷取呼叫堆疊。升級要注意:RLS 已被替換成只會顯示棄用提示的 LSP 伺服器,編輯器請改用 rust-analyzer。

語言變更


  • let PATTERN = EXPR else { ... }; 穩定:模式不符合時執行 else 區塊,該區塊必須發散(return、break、panic! 等),詳見 模式。
  • 一般區塊可以加標籤並用 break 'label 值 提早離開,迴圈標籤見 迴圈。
  • 關聯型別可以帶生命週期、型別與 const 泛型參數(GATs),詳見 進階特徵。
  • 未初始化的整數、浮點數與裸指標立即構成未定義行為;處理未初始化記憶體要用 MaybeUninit,見 unsafe。
  • 新增 let_underscore_drop 與 let_underscore_lock lint;不允許替外部型別實作 Drop。

標準庫重點


  • std::backtrace::Backtrace 穩定,可用來替錯誤附上執行期的堆疊資訊,詳見 std::backtrace。
  • std::io::read_to_string 一次把任何 Read 的內容讀成 String,詳見 std::io。
  • <*const T>::cast_mut、<*mut T>::cast_const 只轉換指標的可變性,詳見 std::ptr。
  • Bound::as_ref 穩定。

Cargo 與工具


  • Linux 上的 -Csplit-debuginfo 穩定,unpacked 輸出多個 .dwo、packed 輸出單一 .dwp,可縮短連結時間。
  • 升級到 LLVM 15;最佳化編譯啟用 MIR 內聯(inlining),實際 crate 的編譯時間改善 3–10%。
  • Cargo 排程會考慮工作優先順序,大型相依圖的建置略快。

相容性注意


  • RLS 被替換成顯示棄用警告的小型 LSP 伺服器,請改用 rust-analyzer,見 開發工具。
  • Layout 的大小向上對齊後不得超過 isize::MAX。
  • PollFn 只在閉包是 Unpin 時才實作 Unpin。
  • 對含 #[non_exhaustive] 變體的列舉使用 as 轉型會產生錯誤。

let-else:取不到就提早離開


let 平常只能接「一定會符合」的模式。let-else 允許可能不符合的模式(例如 Some(x)、Ok(n)):符合時變數綁定在外層作用域,可以繼續使用;不符合時執行 else 區塊,而這個區塊必須離開當前流程。和 if let 相比,成功路徑不必縮排在大括號裡。
範例:
  1. fn parse_pair(line: &str) -> Result<(String, u32), String> {
  2. let Some((key, value)) = line.split_once('=') else {
  3. return Err(format!("缺少等號: {line:?}"));
  4. };
  5. let Ok(n) = value.trim().parse::<u32>() else {
  6. return Err(format!("不是數字: {value:?}"));
  7. };
  8. Ok((key.trim().to_string(), n))
  9. }
  10. fn main() {
  11. for line in ["port = 8080", "timeout", "retries = many"] {
  12. println!("{:?}", parse_pair(line));
  13. }
  14. }

輸出:
  1. Ok(("port", 8080))
  2. Err("缺少等號: \"timeout\"")
  3. Err("不是數字: \" many\"")

注意:else 區塊若沒有 return、break、continue 或 panic! 之類的發散敘述,會編譯失敗。

從具名區塊 break


以前想「在區塊中途帶著值離開」,只能寫一個只跑一次的 loop。現在任何區塊都能加上 'name: 標籤,用 break 'name 值 直接跳到區塊結尾並產生值。它只能跳到所在區塊的結尾,不是任意跳轉的 goto。
範例:
  1. fn grade(score: i32) -> &'static str {
  2. let result = 'check: {
  3. if score < 0 || score > 100 {
  4. break 'check "無效";
  5. }
  6. if score >= 90 {
  7. break 'check "優";
  8. }
  9. if score >= 60 {
  10. break 'check "及格";
  11. }
  12. "不及格"
  13. };
  14. result
  15. }
  16. fn main() {
  17. for s in [95, 72, 40, 120] {
  18. println!("{s}: {}", grade(s));
  19. }
  20. }

輸出:
  1. 95: 優
  2. 72: 及格
  3. 40: 不及格
  4. 120: 無效

泛型關聯型別(GATs)


關聯型別現在可以有自己的泛型參數。最常見的用途是「出借迭代器」:每次 next 回傳的項目借用自迭代器本身,所以項目的生命週期要跟著 &'a mut self 走,這是標準的 Iterator 表達不了的。下面的 Windows 每次借出一段可變的視窗切片,修改會直接寫回內部資料。
範例:
  1. trait LendingIter {
  2. type Item<'a>
  3. where
  4. Self: 'a;
  5. fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;
  6. }
  7. struct Windows {
  8. data: Vec<i32>,
  9. pos: usize,
  10. }
  11. impl LendingIter for Windows {
  12. type Item<'a> = &'a mut [i32];
  13. fn next<'a>(&'a mut self) -> Option<Self::Item<'a>> {
  14. if self.pos + 2 > self.data.len() {
  15. return None;
  16. }
  17. let start = self.pos;
  18. self.pos += 1;
  19. Some(&mut self.data[start..start + 2])
  20. }
  21. }
  22. fn main() {
  23. let mut w = Windows { data: vec![1, 2, 3, 4], pos: 0 };
  24. while let Some(pair) = w.next() {
  25. pair[1] += pair[0];
  26. }
  27. println!("{:?}", w.data);
  28. }

輸出:
  1. [1, 3, 6, 10]

本版新增的棄用 API


本版沒有新增棄用 API。

修補版本


本版沒有修補版本。

已知漏洞


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

仍影響 1.65.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-40030cargoMalicious dependencies can inject arbitrary JavaScript into cargo-generated timing reports1.60.0 起,早於 1.72.01.72.0
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

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

資料來源