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 是泛型參數的簡寫。範例:
- use std::fmt::Display;
- fn evens_squared(limit: u32) -> impl Iterator<Item = u32> {
- (1..=limit).filter(|n| n % 2 == 0).map(|n| n * n)
- }
- fn make_adder(step: i32) -> impl Fn(i32) -> i32 {
- move |x| x + step
- }
- fn show_all(items: impl IntoIterator<Item = impl Display>) -> String {
- items.into_iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ")
- }
- fn main() {
- let squares: Vec<u32> = evens_squared(10).collect();
- println!("{:?}", squares);
- let add5 = make_adder(5);
- println!("{}", add5(10));
- println!("{}", show_all(vec![1.5, 2.25]));
- println!("{}", show_all(["甲", "乙", "丙"]));
- }
輸出:
- [4, 16, 36, 64, 100]
- 15
- 1.5, 2.25
- 甲, 乙, 丙
注意:回傳位置的
impl Trait 只能對應「一個」實際型別;if 兩個分支回傳不同型別的迭代器會編譯失敗,這時仍要用 Box<dyn Trait>,詳見 特徵物件。match 自動處理參考與切片模式
對
&Option<String> 做 match,以前要寫成 &Some(ref n)。現在直接寫 Some(n),編譯器看到被比對的是參考,就自動把 n 綁定成 &String;對 &mut 則綁定成 &mut String,可以直接修改。同一版也能用 [a, b] 這種固定長度的模式比對切片。範例:
- fn greet(name: &Option<String>) -> String {
- match name {
- Some(n) => format!("你好,{}!", n),
- None => String::from("你是誰?"),
- }
- }
- fn shout(name: &mut Option<String>) {
- if let Some(n) = name {
- n.push_str("!!!");
- }
- }
- fn describe(nums: &[i32]) -> String {
- match nums {
- [] => String::from("空的"),
- [x] => format!("只有 {}", x),
- [a, b] => format!("兩個:{} 和 {}", a, b),
- _ => format!("{} 個元素", nums.len()),
- }
- }
- fn main() {
- let mut someone = Some(String::from("Ferris"));
- println!("{}", greet(&someone));
- shout(&mut someone);
- println!("{:?}", someone);
- println!("{}", greet(&None));
- for v in [&[][..], &[7], &[1, 2], &[1, 2, 3]] {
- println!("{}", describe(v));
- }
- }
輸出:
- 你好,Ferris!
- Some("Ferris!!!")
- 你是誰?
- 空的
- 只有 7
- 兩個:1 和 2
- 3 個元素
注意:比對切片時長度不固定,必須有
_ 之類的分支涵蓋其他長度,否則會出現「patterns not covered」的編譯錯誤。main 回傳 Result 與 fs 便利函式
main 回傳 Result 後,就能直接用 ? 處理錯誤;回傳 Err 時程式會以非零狀態碼結束,並把錯誤的 Debug 內容印到標準錯誤。搭配這版新增的 fs::write、fs::read_to_string、fs::read,讀寫整個檔案只要一行。範例:
- use std::error::Error;
- use std::fs;
- fn main() -> Result<(), Box<dyn Error>> {
- let dir = std::env::temp_dir().join(format!("rust126-{}", std::process::id()));
- fs::create_dir_all(&dir)?;
- let path = dir.join("port.txt");
- fs::write(&path, "8080\n")?;
- let text = fs::read_to_string(&path)?;
- let port: u16 = text.trim().parse()?;
- println!("讀到的連接埠:{}", port);
- let bytes = fs::read(&path)?;
- println!("位元組:{:02x?}", bytes);
- let big: u128 = u64::MAX as u128 * 4;
- println!("u128:{}", big);
- fs::remove_dir_all(&dir)?;
- Ok(())
- }
輸出:
- 讀到的連接埠:8080
- 位元組:[38, 30, 38, 30, 0a]
- u128:73786976294838206460
注意:
fs::read_to_string 遇到非 UTF-8 內容會回傳 Err;中途 ? 提早返回時,範例最後的 remove_dir_all 不會執行。本版新增的棄用 API
以下 API 從 Rust 1.26 起標記為棄用(deprecated),新程式不要再使用;說明欄為官方原文。
| 模組 | 項目 | 官方說明 |
|---|---|---|
std::ascii | AsciiExt | use inherent methods instead |
std::ascii | AsciiExt::eq_ignore_ascii_case | use inherent methods instead |
std::ascii | AsciiExt::is_ascii | use inherent methods instead |
std::ascii | AsciiExt::make_ascii_lowercase | use inherent methods instead |
std::ascii | AsciiExt::make_ascii_uppercase | use inherent methods instead |
std::ascii | AsciiExt::Owned | use inherent methods instead |
std::ascii | AsciiExt::to_ascii_lowercase | use inherent methods instead |
std::ascii | AsciiExt::to_ascii_uppercase | use inherent methods instead |
修補版本
| 版本 | 發布日期 | 含安全修補 | 內容(官方原文) |
|---|---|---|---|
1.26.1 | 2018-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.2 | 2018-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-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 |
| CVE-2024-24576 | std | std::process::Command did not properly escape arguments of batch files on Windows | 早於 1.77.2 | 1.77.2 |
| CVE-2023-38497 | cargo | Cargo not respecting umask when extracting crate archives | 早於 1.71.1 | 1.71.1 |
| CVE-2022-46176 | cargo | Cargo did not verify SSH host keys | 早於 1.66.1 | 1.66.1 |
| CVE-2022-36113 | cargo | Extracting malicious crates can corrupt arbitrary files | 早於 1.64.0 | 1.64.0 |
| CVE-2022-36114 | cargo | Extracting malicious crates can fill the file system | 早於 1.64.0 | 1.64.0 |
| CVE-2022-21658 | std | Race condition in std::fs::remove_dir_all | 早於 1.58.1 | 1.58.1 |
| CVE-2021-42574 | rustc | rustc and bidirectional-override codepoints in source code | 早於 1.56.1 | 1.56.1 |
| CVE-2021-28878 | std | Zip may call __iterator_get_unchecked twice with the same index | 1.14.0 起,早於 1.52.0 | 1.52.0 |
| CVE-2021-28879 | std | Zip can cause buffer overflow when a consumed Zip iterator is used again | 1.14.0 起,早於 1.52.0 | 1.52.0 |
| CVE-2021-28876 | std | Panic safety issue in Zip specialization | 1.14.0 起,早於 1.52.0 | 1.52.0 |
| CVE-2021-28875 | std | Logic bug in Read can cause buffer overflow in read_to_end() | 1.20.0 起,早於 1.50.0 | 1.50.0 |
| CVE-2021-28877 | std | TrustedRandomAccess specialization composes incorrectly for nested iter::Zips | 1.11.0 起,早於 1.51.0 | 1.51.0 |
| CVE-2020-36317 | std | String::retain allows safely creating invalid strings when abusing panic | 1.26.0 起,早於 1.49.0 | 1.49.0 |
| CVE-2021-29922 | std | Improper Input Validation of octal literals in std::net | 早於 1.53.0 | 1.53.0 |
| CVE-2018-1000810 | std | Buffer overflow vulnerability in str::repeat() | 1.26.0 起,早於 1.29.1 | 1.29.1 |
| CVE-2019-1010299 | std | vec_deque::Iter has unsound Debug implementation | 1.18.0 起,早於 1.30.0 | 1.30.0 |
| CVE-2018-1000622 | rustdoc | Uncontrolled search path element vulnerability in rustdoc plugins | 早於 1.27.1 | 1.27.1 |
| CVE-2018-25008 | std | Insufficient synchronization in Arc::get_mut | 1.3.0 起,早於 1.29.0 | 1.29.0 |
本版已停止支援,不會再修正這些漏洞;請升級到
1.100.1。