Rust 1.74

最後更新


Rust 1.74 發布於 2023-11-16,目前最新修補版為 1.74.1,已停止支援,請升級到 1.100.1。

版本介紹


Rust 1.74 讓 Cargo.toml 可以用 [lints] 表設定 lint 等級,不必再在每個 crate 根部寫 #![deny(...)] 或透過 RUSTFLAGS 影響整個建置;Cargo 也加入憑證提供者(credential provider)與需要驗證的私有 registry。語言方面,async fn 與 -> impl Trait 的回傳型別終於可以提到 Self 與關聯型別。升級要注意:新的 From<&[T; N]> for Vec<T> 可能讓過度泛型的程式型別推論失敗;Apple 平台的最低系統版本提高。

語言變更


  • 不透明回傳型別(async fn、-> impl Trait)可以提到 Self 與帶父層生命週期的關聯型別,詳見 進階特徵。
  • private_in_public lint 被 private_interfaces 與 private_bounds 取代,模組可見性見 模組系統。
  • 允許明確寫出 #[repr(Rust)];async 區塊改用以 MIR 為基礎的 drop 追蹤。

標準庫重點


  • core::num::Saturating 穩定:運算溢位時停在最大或最小值,詳見 std::num。
  • std::io::Error::other 用任意錯誤建立 ErrorKind::Other 的 I/O 錯誤,詳見 std::io 與 自訂錯誤。
  • Vec<T> 可從 &[T; N]、&mut [T; N] 轉換;Rc<[T]>、Arc<[T]> 可從 [T; N] 轉換,詳見 Vec。
  • OsStr::as_encoded_bytes、OsString::into_encoded_bytes 與對應的 from_encoded_bytes_unchecked 穩定,詳見 std::ffi。
  • io::Stdout、io::Stderr 可以轉成 process::Stdio,讓子行程直接寫到父行程的輸出,詳見 std::process。
  • char 可用 TryFrom 轉成 u16;str::is_ascii 與 mem::transmute_copy 可在 const 環境使用。

Cargo 與工具


  • Cargo.toml 新增 [lints.rust]、[lints.clippy] 等表,也能放在 [workspace.lints] 由成員以 [lints] workspace = true 繼承,詳見 Cargo 與 工作區。
  • 憑證提供者與 registry 驗證穩定:可用作業系統的安全儲存保管 token,私有 registry 可要求所有操作都需驗證。
  • --keep-going 建置參數穩定;cargo clean 新增 --dry-run,-n 是 --dry-run 的別名。
  • cargo update 的套件名稱可直接當位置參數;--aggressive 更名為 --recursive;--help 輸出加上樣式。

相容性注意


  • impl From<{&,&mut} [T; N]> for Vec<T> 可能讓過度泛型的程式(例如搭配 AsRef 與 Into<Vec>)型別推論失敗。
  • Cell::swap 在兩個 Cell 部分重疊時會 panic。
  • Apple 平台的最低支援系統版本提高;--extern 拒絕無效的 crate 名稱。

Saturating:會「停住」的整數


血量、庫存、音量這類值,減到底就該停在 0,加到頂就該停在上限。Saturating<T> 包住整數後,+、-、+= 等運算一律飽和計算,不會溢位也不會 panic;.0 取回內部的值。它與 Wrapping<T>(溢位時繞回)是一對,整數溢位的觀念見 整數。
範例:
  1. use std::num::Saturating;
  2. fn main() {
  3. let mut hp = Saturating(10u8);
  4. hp -= 30;
  5. println!("{hp}");
  6. hp += Saturating(250);
  7. hp += Saturating(250);
  8. println!("{} {}", hp, hp.0);
  9. }

輸出:
  1. 0
  2. 255 255

io::Error::other:把任何錯誤包成 I/O 錯誤


函式回傳 io::Result<T> 時,常需要把別種錯誤(例如解析錯誤)轉進來。以前寫 io::Error::new(io::ErrorKind::Other, e),現在 io::Error::other(e) 一步完成,也能直接傳給 map_err。原本的錯誤會保留,Display 時印出它的訊息。
範例:
  1. use std::io;
  2. fn read_port(s: &str) -> io::Result<u16> {
  3. s.parse::<u16>().map_err(io::Error::other)
  4. }
  5. fn main() {
  6. println!("{:?}", read_port("8080").ok());
  7. let err = read_port("99999").unwrap_err();
  8. println!("{:?} {}", err.kind(), err);
  9. }

輸出:
  1. Some(8080)
  2. Other number too large to fit in target type

不透明回傳型別可以提到 Self 與關聯型別


以前在帶生命週期參數的型別上,-> impl Iterator<Item = Self> 或 -> impl Iterator<Item = S::Key> 會得到「return type cannot contain a projection or Self that references lifetimes from a parent scope」錯誤,只能改寫出完整型別名稱。從這版起,下面兩種寫法都能直接編譯:View<'a, S> 回傳關聯型別 S::Key 的迭代器,Word<'a> 回傳 Self 的迭代器。
範例:
  1. trait Store {
  2. type Key;
  3. fn keys(&self) -> Vec<Self::Key>;
  4. }
  5. struct Users(Vec<u32>);
  6. impl Store for Users {
  7. type Key = u32;
  8. fn keys(&self) -> Vec<u32> {
  9. self.0.clone()
  10. }
  11. }
  12. struct View<'a, S: Store>(&'a S);
  13. impl<'a, S: Store> View<'a, S> {
  14. fn iter_keys(&self) -> impl Iterator<Item = S::Key> {
  15. self.0.keys().into_iter()
  16. }
  17. }
  18. struct Word<'a>(&'a str);
  19. impl<'a> Word<'a> {
  20. fn split(text: &'a str) -> impl Iterator<Item = Self> {
  21. text.split_whitespace().map(Word)
  22. }
  23. }
  24. fn main() {
  25. let users = Users(vec![7, 3, 9]);
  26. let v = View(&users);
  27. println!("{:?}", v.iter_keys().collect::<Vec<_>>());
  28. let lens: Vec<usize> = Word::split("hello rust world").map(|w| w.0.len()).collect();
  29. println!("{lens:?}");
  30. }

輸出:
  1. [7, 3, 9]
  2. [5, 4, 5]

本版新增的棄用 API


本版沒有新增棄用 API。

修補版本


版本發布日期含安全修補內容(官方原文)
1.74.12023-12-07否Resolved spurious STATUS_ACCESS_VIOLATIONs in LLVM;Clarify guarantees for std::mem::discriminant;Fix some subtyping-related regressions

已知漏洞


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

仍影響 1.74.1


編號元件摘要(官方原文)影響範圍修正於
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

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

資料來源