Edition 與語言演進
最後更新
Edition 是 Rust 引入「不相容變更」的機制:每個 crate 自己選擇要用哪一版語法規則,新舊 crate 仍可互相使用。
Edition 是什麼
Rust 承諾「穩定而不停滯」:Rust 1.0 之後,用穩定版寫出的程式,新版編譯器仍要能編譯。但有些改進一定會打破舊程式,最典型的是新增關鍵字:如果
async 突然變成關鍵字,let async = 1; 就會壞掉。解法是 edition(版次):不相容的變更只在新的 edition 生效,crate 要自己選擇升級。目前有四個 edition:
| Edition | 隨哪個版本穩定 | 代表變更 |
|---|---|---|
| 2015 | Rust 1.0 | 最初的語言,rustc 不指定時的預設值 |
| 2018 | Rust 1.31 | 模組路徑改版、async/dyn 成為關鍵字 |
| 2021 | Rust 1.56 | 陣列 into_iter 取值、閉包分欄位捕獲 |
| 2024 | Rust 1.85 | unsafe extern、if let 暫存值範圍、let chains |
Edition 不是編譯器版本:Rust 1.100 可以編譯任何 edition 的程式碼。
cargo new 會自動選最新的 edition,寫在 Cargo.toml 的 edition = "2024";直接用 rustc 時以 --edition 2024 指定。各版本的完整變動見 版本總覽。同一段程式在不同 edition 的結果
async 在 2015 edition 只是普通名稱,2018 起成為關鍵字。同一個檔案用不同 --edition 編譯,結果不同:- fn main() {
- let async = 5;
- println!("async = {}", async);
- }
rustc --edition 2015 kw.rs && ./kw 的輸出:- async = 5
rustc --edition 2024 kw.rs,這段無法編譯:- error: expected identifier, found keyword `async`
- --> kw.rs:2:9
- |
- 2 | let async = 5;
- | ^^^^^ expected identifier, found keyword
- |
- help: escape `async` to use it as an identifier
- |
- 2 | let r#async = 5;
要在新 edition 使用和關鍵字同名的識別字,加上
r# 前綴(原始識別字,raw identifier)。gen 在 2024 edition 也被保留為關鍵字,所以一樣要寫 r#gen:- fn main() {
- let r#async = 5;
- let r#gen = "產生器";
- println!("async = {}, gen = {}", r#async, r#gen);
- }
輸出:
- async = 5, gen = 產生器
相容性承諾:不同 edition 的 crate 可以互相使用
Edition 最重要的規則:不同 edition 的 crate 必須能無縫互通。你的專案升級到 2024,不需要等所有相依套件一起升級;相依套件停在 2015,你也照樣能用。所有 edition 最後都編譯成相同的內部表示,差異只在「表面語法」。
下面的 工作區 中,
old_lib 是 2015 edition,匯出名為 async 與 gen 的函式;2024 edition 的 app 用 r# 呼叫它們:- interop/
- ├── Cargo.toml [workspace] members = ["old_lib", "app"]
- ├── old_lib/
- │ ├── Cargo.toml edition = "2015"
- │ └── src/lib.rs
- └── app/
- ├── Cargo.toml edition = "2024",相依 old_lib = { path = "../old_lib" }
- └── src/main.rs
old_lib/src/lib.rs:- pub fn async() -> &'static str {
- "我是 2015 edition 的 async 函式"
- }
- pub fn gen(n: u32) -> Vec<u32> {
- (0..n).collect()
- }
app/src/main.rs:- fn main() {
- println!("{}", old_lib::r#async());
- println!("{:?}", old_lib::r#gen(3));
- }
輸出(
cargo run -q -p app):- 我是 2015 edition 的 async 函式
- [0, 1, 2]
各 edition 的主要變更
以下依官方 Edition Guide 整理重點,範例都以 2024 edition 編譯。
Rust 2018:路徑與 dyn
| 變更 | 說明 |
|---|---|
| 路徑改版 | 用 crate:: 指本 crate 根目錄;使用外部 crate 不必再寫 extern crate |
| 新關鍵字 | async、await、dyn、try |
dyn Trait | 特徵物件寫成 Box<dyn Trait>,舊寫法 Box<Trait> 在 2021 成為錯誤 |
| 特徵方法的匿名參數 | fn f(u8); 不再允許,參數必須有名字 |
非詞法生命週期(NLL)最早隨 2018 edition 推出,Rust 1.36 起 2015 edition 也啟用,現在不分 edition。下例用
crate:: 路徑引入模組內的特徵,並用 dyn 表示特徵物件:- mod shapes {
- pub trait Area {
- fn area(&self) -> f64;
- }
- pub struct Rect(pub f64, pub f64);
- impl Area for Rect {
- fn area(&self) -> f64 {
- self.0 * self.1
- }
- }
- }
- mod report {
- use crate::shapes::Area;
- pub fn total(items: &[Box<dyn Area>]) -> f64 {
- items.iter().map(|s| s.area()).sum()
- }
- }
- fn main() {
- let items: Vec<Box<dyn shapes::Area>> = vec![
- Box::new(shapes::Rect(2.0, 3.0)),
- Box::new(shapes::Rect(1.0, 4.0)),
- ];
- println!("{}", report::total(&items));
- }
輸出:
- 10
Rust 2021:陣列、閉包與 prelude
| 變更 | 說明 |
|---|---|
陣列的 into_iter() | 取得元素本身(舊 edition 是取參考) |
| 閉包分欄位捕獲 | 閉包只捕獲用到的欄位,例如只借 s.hits,不鎖住整個 s |
| prelude 新增 | TryFrom、TryInto、FromIterator 不必 use |
$x:pat | 巨集的 pat 片段可以匹配 1 | 2 這種或模式 |
panic! 一致性 | panic! 的第一個參數一律是格式字串,和 println! 相同 |
| 保留前綴語法 | ident#、ident"..." 保留給未來使用,C 字串字面值 c"..." 就是因此得以加入 |
| Cargo | 預設使用 resolver 2 |
下例的每一段在 2018 edition 都編譯不過:
words.into_iter() 得到 &String 而無法收集成 Vec<String>(E0277)、u8::try_from 找不到(E0599,TryFrom 不在 prelude)、閉包借走整個 s 使 s.name 無法讀取(E0502)、is_small!(1 | 2 | 3) 出現 no rules expected。2021 起全部成立:- struct Settings {
- name: String,
- hits: u32,
- }
- macro_rules! is_small {
- ($p:pat) => {
- matches!(3, $p)
- };
- }
- fn main() {
- let words = [String::from("a"), String::from("b")];
- let owned: Vec<String> = words.into_iter().collect();
- println!("{owned:?}");
- let mut s = Settings { name: String::from("demo"), hits: 0 };
- let mut bump = || s.hits += 1;
- println!("名稱:{}", s.name);
- bump();
- bump();
- println!("次數:{}", s.hits);
- let byte = u8::try_from(300_i32).unwrap_or(u8::MAX);
- println!("{byte}");
- println!("{}", is_small!(1 | 2 | 3));
- }
輸出:
- ["a", "b"]
- 名稱:demo
- 次數:2
- 255
- true
Rust 2024:unsafe 更明確、暫存值範圍更合理
| 變更 | 說明 |
|---|---|
unsafe extern | extern 區塊必須寫成 unsafe extern,見 FFI |
| 不安全屬性 | #[no_mangle] 等要寫成 #[unsafe(no_mangle)] |
unsafe_op_in_unsafe_fn | unsafe fn 本體內的不安全操作也要包 unsafe { },見 unsafe Rust |
static mut 參考 | 對 static mut 建立參考預設是錯誤 |
if let 暫存值範圍 | if let 條件中的暫存值在進入 else 前就釋放 |
| 尾端運算式暫存值 | 區塊最後一個運算式的暫存值在區域變數之前釋放 |
| let chains | if let ... && let ... && 條件,Rust 1.88 起只在 2024 edition 可用(見 Rust 1.88) |
impl Trait 回傳值 | 預設捕獲所有泛型與生命週期參數 |
Box<[T]> | into_iter() 取得元素本身 |
| prelude 新增 | Future、IntoFuture |
| 新的 unsafe 函式 | std::env::set_var、remove_var 變成 unsafe fn |
gen 關鍵字 | 保留給未來的產生器 |
巨集 expr 片段 | 也能匹配 const { } 與 _;要舊行為用 expr_2021(Rust 1.83 起) |
| Cargo | 預設 resolver 3,會考慮 rust-version 挑選相依版本 |
下例示範三項:
if let 條件中 cell.borrow() 產生的暫存值,在 2024 edition 進入 else 前就釋放,所以 borrow_mut() 成功;let chains 把多層 if let 串在一起;Box<[String]> 的 into_iter() 直接取得 String。- use std::cell::RefCell;
- fn main() {
- let cell = RefCell::new(None::<i32>);
- if let Some(v) = *cell.borrow() {
- println!("已有值 {v}");
- } else {
- *cell.borrow_mut() = Some(1);
- println!("寫入 1");
- }
- let input = Some("42");
- if let Some(text) = input
- && let Ok(n) = text.parse::<i32>()
- && n > 10
- {
- println!("大於 10 的數字:{n}");
- }
- let boxed: Box<[String]> = vec![String::from("x"), String::from("y")].into_boxed_slice();
- let joined: String = boxed.into_iter().collect();
- println!("{joined}");
- }
輸出:
- 寫入 1
- 大於 10 的數字:42
- xy
同樣的
if let 在 2021 edition 會在執行時 panic:borrow() 的暫存值活到整個 if let ... else 結束,else 裡的 borrow_mut() 因此失敗。scope.rs:- use std::cell::RefCell;
- fn main() {
- let cell = RefCell::new(None::<i32>);
- if let Some(v) = *cell.borrow() {
- println!("已有值 {v}");
- } else {
- *cell.borrow_mut() = Some(1);
- println!("寫入 1");
- }
- println!("{:?}", cell.borrow());
- }
rustc --edition 2024 scope.rs && ./scope 的輸出:- 寫入 1
- Some(1)
改用
--edition 2021 編譯執行,標準錯誤輸出的前兩行:- thread 'main' (<執行緒 ID>) panicked at scope.rs:8:15:
- RefCell already borrowed
升級 edition:cargo fix --edition
用 cargo fix 自動遷移
升級步驟:
- 先確認在目前的 edition 下能編譯、測試通過
- 執行
cargo fix --edition,Cargo 會把程式碼改成新舊 edition 都能接受的寫法 - 把
Cargo.toml的edition改成新值 - 重新編譯、跑測試,處理自動修正沒涵蓋到的地方
下面是一個 2021 edition 的專案,用到了沒加
unsafe 的 extern 區塊和名為 gen 的變數,兩者在 2024 都不合法。src/main.rs:- use std::ffi::c_int;
- extern "C" {
- fn abs(x: c_int) -> c_int;
- }
- fn main() {
- let gen = unsafe { abs(-3) };
- println!("gen = {}", gen);
- }
在專案目錄執行
cargo fix --edition --allow-no-vcs(--allow-no-vcs 允許在不是 git 儲存庫的目錄中修改;有 git 時建議先 commit,改用預設行為):- Migrating Cargo.toml from 2021 edition to 2024
- Checking upgrade v0.1.0 (<專案路徑>)
- Migrating src/main.rs from 2021 edition to 2024
- Fixed src/main.rs (3 fixes)
- Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.09s
<專案路徑> 與耗時會因機器而異。修正後的 src/main.rs:- use std::ffi::c_int;
- unsafe extern "C" {
- fn abs(x: c_int) -> c_int;
- }
- fn main() {
- let r#gen = unsafe { abs(-3) };
- println!("gen = {}", r#gen);
- }
再把
Cargo.toml 改成 edition = "2024",cargo run -q 的輸出:- gen = 3
注意:自動遷移不保證完整。語意改變的項目(例如
if let 暫存值範圍、尾端運算式暫存值)可能需要人工確認;遷移時看到的 rust_2024_compatibility 警告都值得逐一讀過。重點整理
- Edition 讓 Rust 能做不相容變更而不破壞舊程式碼;目前有 2015、2018、2021、2024 四個
- Edition 由每個 crate 在
Cargo.toml自己選,不同 edition 的 crate 可以互相相依 - 2018 改了模組路徑並加入
dyn、async;2021 改了陣列into_iter與閉包捕獲;2024 讓unsafe更明確並調整暫存值範圍 - 新 edition 的關鍵字和舊程式碼撞名時,用
r#名稱呼叫 - 升級流程:
cargo fix --edition→ 改Cargo.toml的edition→ 編譯測試