Rust 1.26

最後更新


Rust 1.26 發布於 2018-05-10,目前最新修補版為 1.26.2,已停止支援,請升級到 1.100.1。

版本介紹


Rust 1.26 可能是 1.0 之後功能最多的一版:impl Trait 讓函式可以回傳「某個實作了特徵的型別」而不必寫出冗長的實際型別;match 會自動處理參考,不必再寫一堆 & 和 ref;main 可以回傳 Result,直接在 main 裡用 ?。另外還有包含結尾的範圍 ..=、128 位元整數與基本的切片模式。官方也從這版起推薦《The Rust Programming Language》第二版。

語言變更


  • impl Trait 穩定,可用在回傳型別與參數位置,詳見 特徵。
  • 模式比對自動套用解參考與借用(default binding modes),詳見 模式。
  • main 可以回傳 Result<(), E>(E: Debug),詳見 Result 錯誤處理。
  • 包含結尾的範圍 0..=10 穩定,詳見 迴圈。
  • 新增 u128、i128,詳見 整數。
  • 固定長度的切片模式(如 [a, b])穩定,詳見 match。
  • '_ 生命週期穩定,可用在任何能省略生命週期的位置,詳見 生命週期。
  • 捕獲的變數都可 Copy/Clone 時,閉包本身也實作 Copy/Clone,詳見 閉包。
  • 常數運算式可以做更多事,例如索引常數陣列、使用元組結構建構函式。

標準庫重點


  • 新增 fs::read、fs::read_to_string、fs::write,一行讀寫整個檔案,詳見 std::fs。
  • 新增 hash_map::Entry::and_modify 與 btree_map::Entry::and_modify,詳見 HashMap。
  • 新增 Box::leak、Option::cloned、String::retain、slice::rotate_left、slice::rotate_right、process::id。
  • 原始指標新增 add、sub、read、write 等方法,詳見 std::ptr。
  • Debug 格式支援十六進位,例如 {:02x?},詳見 std::fmt。
  • 新增 From<u16> for usize 與 From<u8>、From<i16> for isize;標準庫所有巨集都允許結尾逗號。

Cargo 與工具


  • Cargo 的版本號改為與 Rust 一致;解析 lock 檔更快,較少需要手動 cargo update,詳見 Cargo。
  • rustc 新增 --remap-path-prefix;wasm32-unknown-unknown 預設改用 LLD 連結。

相容性注意


  • 解參考的結果不再被提升為 'static。
  • use std::ops::Fn as dyn; 這類把特徵別名為 dyn 的寫法失效。
  • ".e0" 不再被解析為 0.0;rustdoc 移除 Hoedown。

impl Trait


閉包和迭代器鏈的實際型別又長又寫不出來。以前只能回傳 Box<dyn Trait>,代價是堆積配置與動態分派。-> impl Trait 表示「回傳某個實作了此特徵的型別」,實際型別由編譯器推斷,呼叫端只能使用特徵提供的方法。寫在參數位置時,x: impl Trait 是泛型參數的簡寫。
範例:
  1. use std::fmt::Display;
  2. fn evens_squared(limit: u32) -> impl Iterator<Item = u32> {
  3. (1..=limit).filter(|n| n % 2 == 0).map(|n| n * n)
  4. }
  5. fn make_adder(step: i32) -> impl Fn(i32) -> i32 {
  6. move |x| x + step
  7. }
  8. fn show_all(items: impl IntoIterator<Item = impl Display>) -> String {
  9. items.into_iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ")
  10. }
  11. fn main() {
  12. let squares: Vec<u32> = evens_squared(10).collect();
  13. println!("{:?}", squares);
  14. let add5 = make_adder(5);
  15. println!("{}", add5(10));
  16. println!("{}", show_all(vec![1.5, 2.25]));
  17. println!("{}", show_all(["甲", "乙", "丙"]));
  18. }

輸出:
  1. [4, 16, 36, 64, 100]
  2. 15
  3. 1.5, 2.25
  4. 甲, 乙, 丙

注意:回傳位置的 impl Trait 只能對應「一個」實際型別;if 兩個分支回傳不同型別的迭代器會編譯失敗,這時仍要用 Box<dyn Trait>,詳見 特徵物件。

match 自動處理參考與切片模式


對 &Option<String> 做 match,以前要寫成 &Some(ref n)。現在直接寫 Some(n),編譯器看到被比對的是參考,就自動把 n 綁定成 &String;對 &mut 則綁定成 &mut String,可以直接修改。同一版也能用 [a, b] 這種固定長度的模式比對切片。
範例:
  1. fn greet(name: &Option<String>) -> String {
  2. match name {
  3. Some(n) => format!("你好,{}!", n),
  4. None => String::from("你是誰?"),
  5. }
  6. }
  7. fn shout(name: &mut Option<String>) {
  8. if let Some(n) = name {
  9. n.push_str("!!!");
  10. }
  11. }
  12. fn describe(nums: &[i32]) -> String {
  13. match nums {
  14. [] => String::from("空的"),
  15. [x] => format!("只有 {}", x),
  16. [a, b] => format!("兩個:{} 和 {}", a, b),
  17. _ => format!("{} 個元素", nums.len()),
  18. }
  19. }
  20. fn main() {
  21. let mut someone = Some(String::from("Ferris"));
  22. println!("{}", greet(&someone));
  23. shout(&mut someone);
  24. println!("{:?}", someone);
  25. println!("{}", greet(&None));
  26. for v in [&[][..], &[7], &[1, 2], &[1, 2, 3]] {
  27. println!("{}", describe(v));
  28. }
  29. }

輸出:
  1. 你好,Ferris!
  2. Some("Ferris!!!")
  3. 你是誰?
  4. 空的
  5. 只有 7
  6. 兩個:1 和 2
  7. 3 個元素

注意:比對切片時長度不固定,必須有 _ 之類的分支涵蓋其他長度,否則會出現「patterns not covered」的編譯錯誤。

main 回傳 Result 與 fs 便利函式


main 回傳 Result 後,就能直接用 ? 處理錯誤;回傳 Err 時程式會以非零狀態碼結束,並把錯誤的 Debug 內容印到標準錯誤。搭配這版新增的 fs::write、fs::read_to_string、fs::read,讀寫整個檔案只要一行。
範例:
  1. use std::error::Error;
  2. use std::fs;
  3. fn main() -> Result<(), Box<dyn Error>> {
  4. let dir = std::env::temp_dir().join(format!("rust126-{}", std::process::id()));
  5. fs::create_dir_all(&dir)?;
  6. let path = dir.join("port.txt");
  7. fs::write(&path, "8080\n")?;
  8. let text = fs::read_to_string(&path)?;
  9. let port: u16 = text.trim().parse()?;
  10. println!("讀到的連接埠:{}", port);
  11. let bytes = fs::read(&path)?;
  12. println!("位元組:{:02x?}", bytes);
  13. let big: u128 = u64::MAX as u128 * 4;
  14. println!("u128:{}", big);
  15. fs::remove_dir_all(&dir)?;
  16. Ok(())
  17. }

輸出:
  1. 讀到的連接埠:8080
  2. 位元組:[38, 30, 38, 30, 0a]
  3. u128:73786976294838206460

注意:fs::read_to_string 遇到非 UTF-8 內容會回傳 Err;中途 ? 提早返回時,範例最後的 remove_dir_all 不會執行。

本版新增的棄用 API


以下 API 從 Rust 1.26 起標記為棄用(deprecated),新程式不要再使用;說明欄為官方原文。
模組項目官方說明
std::asciiAsciiExtuse inherent methods instead
std::asciiAsciiExt::eq_ignore_ascii_caseuse inherent methods instead
std::asciiAsciiExt::is_asciiuse inherent methods instead
std::asciiAsciiExt::make_ascii_lowercaseuse inherent methods instead
std::asciiAsciiExt::make_ascii_uppercaseuse inherent methods instead
std::asciiAsciiExt::Owneduse inherent methods instead
std::asciiAsciiExt::to_ascii_lowercaseuse inherent methods instead
std::asciiAsciiExt::to_ascii_uppercaseuse inherent methods instead

修補版本


版本發布日期含安全修補內容(官方原文)
1.26.12018-05-29否RLS now works on Windows.;Rustfmt stopped badly formatting text in some cases.;fn main() -> impl Trait no longer works for non-Termination trait. This reverts an accidental stabilization.;NaN > NaN no longer returns true in const-fn contexts.;Prohibit using turbofish for impl Trait in method arguments.
1.26.22018-06-05否The borrow checker was fixed to avoid unsoundness when using match ergonomics.

已知漏洞


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

仍影響 1.26.2


編號元件摘要(官方原文)影響範圍修正於
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
CVE-2021-42574rustcrustc and bidirectional-override codepoints in source code早於 1.56.11.56.1
CVE-2021-28878stdZip may call __iterator_get_unchecked twice with the same index1.14.0 起,早於 1.52.01.52.0
CVE-2021-28879stdZip can cause buffer overflow when a consumed Zip iterator is used again1.14.0 起,早於 1.52.01.52.0
CVE-2021-28876stdPanic safety issue in Zip specialization1.14.0 起,早於 1.52.01.52.0
CVE-2021-28875stdLogic bug in Read can cause buffer overflow in read_to_end()1.20.0 起,早於 1.50.01.50.0
CVE-2021-28877stdTrustedRandomAccess specialization composes incorrectly for nested iter::Zips1.11.0 起,早於 1.51.01.51.0
CVE-2020-36317stdString::retain allows safely creating invalid strings when abusing panic1.26.0 起,早於 1.49.01.49.0
CVE-2021-29922stdImproper Input Validation of octal literals in std::net早於 1.53.01.53.0
CVE-2018-1000810stdBuffer overflow vulnerability in str::repeat()1.26.0 起,早於 1.29.11.29.1
CVE-2019-1010299stdvec_deque::Iter has unsound Debug implementation1.18.0 起,早於 1.30.01.30.0
CVE-2018-1000622rustdocUncontrolled search path element vulnerability in rustdoc plugins早於 1.27.11.27.1
CVE-2018-25008stdInsufficient synchronization in Arc::get_mut1.3.0 起,早於 1.29.01.29.0

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

資料來源