Edition 與語言演進

最後更新


Edition 是 Rust 引入「不相容變更」的機制:每個 crate 自己選擇要用哪一版語法規則,新舊 crate 仍可互相使用。

Edition 是什麼


Rust 承諾「穩定而不停滯」:Rust 1.0 之後,用穩定版寫出的程式,新版編譯器仍要能編譯。但有些改進一定會打破舊程式,最典型的是新增關鍵字:如果 async 突然變成關鍵字,let async = 1; 就會壞掉。
解法是 edition(版次):不相容的變更只在新的 edition 生效,crate 要自己選擇升級。目前有四個 edition:
Edition隨哪個版本穩定代表變更
2015Rust 1.0最初的語言,rustc 不指定時的預設值
2018Rust 1.31模組路徑改版、async/dyn 成為關鍵字
2021Rust 1.56陣列 into_iter 取值、閉包分欄位捕獲
2024Rust 1.85unsafe 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 編譯,結果不同:
  1. fn main() {
  2. let async = 5;
  3. println!("async = {}", async);
  4. }

rustc --edition 2015 kw.rs && ./kw 的輸出:
  1. async = 5

rustc --edition 2024 kw.rs,這段無法編譯:
  1. error: expected identifier, found keyword `async`
  2. --> kw.rs:2:9
  3. |
  4. 2 | let async = 5;
  5. | ^^^^^ expected identifier, found keyword
  6. |
  7. help: escape `async` to use it as an identifier
  8. |
  9. 2 | let r#async = 5;

要在新 edition 使用和關鍵字同名的識別字,加上 r# 前綴(原始識別字,raw identifier)。gen 在 2024 edition 也被保留為關鍵字,所以一樣要寫 r#gen:
  1. fn main() {
  2. let r#async = 5;
  3. let r#gen = "產生器";
  4. println!("async = {}, gen = {}", r#async, r#gen);
  5. }

輸出:
  1. async = 5, gen = 產生器

相容性承諾:不同 edition 的 crate 可以互相使用


Edition 最重要的規則:不同 edition 的 crate 必須能無縫互通。你的專案升級到 2024,不需要等所有相依套件一起升級;相依套件停在 2015,你也照樣能用。所有 edition 最後都編譯成相同的內部表示,差異只在「表面語法」。
下面的 工作區 中,old_lib 是 2015 edition,匯出名為 async 與 gen 的函式;2024 edition 的 app 用 r# 呼叫它們:
  1. interop/
  2. ├── Cargo.toml [workspace] members = ["old_lib", "app"]
  3. ├── old_lib/
  4. │ ├── Cargo.toml edition = "2015"
  5. │ └── src/lib.rs
  6. └── app/
  7. ├── Cargo.toml edition = "2024",相依 old_lib = { path = "../old_lib" }
  8. └── src/main.rs

old_lib/src/lib.rs:
  1. pub fn async() -> &'static str {
  2. "我是 2015 edition 的 async 函式"
  3. }
  4. pub fn gen(n: u32) -> Vec<u32> {
  5. (0..n).collect()
  6. }

app/src/main.rs:
  1. fn main() {
  2. println!("{}", old_lib::r#async());
  3. println!("{:?}", old_lib::r#gen(3));
  4. }

輸出(cargo run -q -p app):
  1. 我是 2015 edition 的 async 函式
  2. [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 表示特徵物件:
  1. mod shapes {
  2. pub trait Area {
  3. fn area(&self) -> f64;
  4. }
  5. pub struct Rect(pub f64, pub f64);
  6. impl Area for Rect {
  7. fn area(&self) -> f64 {
  8. self.0 * self.1
  9. }
  10. }
  11. }
  12. mod report {
  13. use crate::shapes::Area;
  14. pub fn total(items: &[Box<dyn Area>]) -> f64 {
  15. items.iter().map(|s| s.area()).sum()
  16. }
  17. }
  18. fn main() {
  19. let items: Vec<Box<dyn shapes::Area>> = vec![
  20. Box::new(shapes::Rect(2.0, 3.0)),
  21. Box::new(shapes::Rect(1.0, 4.0)),
  22. ];
  23. println!("{}", report::total(&items));
  24. }

輸出:
  1. 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 起全部成立:
  1. struct Settings {
  2. name: String,
  3. hits: u32,
  4. }
  5. macro_rules! is_small {
  6. ($p:pat) => {
  7. matches!(3, $p)
  8. };
  9. }
  10. fn main() {
  11. let words = [String::from("a"), String::from("b")];
  12. let owned: Vec<String> = words.into_iter().collect();
  13. println!("{owned:?}");
  14. let mut s = Settings { name: String::from("demo"), hits: 0 };
  15. let mut bump = || s.hits += 1;
  16. println!("名稱:{}", s.name);
  17. bump();
  18. bump();
  19. println!("次數:{}", s.hits);
  20. let byte = u8::try_from(300_i32).unwrap_or(u8::MAX);
  21. println!("{byte}");
  22. println!("{}", is_small!(1 | 2 | 3));
  23. }

輸出:
  1. ["a", "b"]
  2. 名稱:demo
  3. 次數:2
  4. 255
  5. true

Rust 2024:unsafe 更明確、暫存值範圍更合理


變更說明
unsafe externextern 區塊必須寫成 unsafe extern,見 FFI
不安全屬性#[no_mangle] 等要寫成 #[unsafe(no_mangle)]
unsafe_op_in_unsafe_fnunsafe fn 本體內的不安全操作也要包 unsafe { },見 unsafe Rust
static mut 參考對 static mut 建立參考預設是錯誤
if let 暫存值範圍if let 條件中的暫存值在進入 else 前就釋放
尾端運算式暫存值區塊最後一個運算式的暫存值在區域變數之前釋放
let chainsif 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。
  1. use std::cell::RefCell;
  2. fn main() {
  3. let cell = RefCell::new(None::<i32>);
  4. if let Some(v) = *cell.borrow() {
  5. println!("已有值 {v}");
  6. } else {
  7. *cell.borrow_mut() = Some(1);
  8. println!("寫入 1");
  9. }
  10. let input = Some("42");
  11. if let Some(text) = input
  12. && let Ok(n) = text.parse::<i32>()
  13. && n > 10
  14. {
  15. println!("大於 10 的數字:{n}");
  16. }
  17. let boxed: Box<[String]> = vec![String::from("x"), String::from("y")].into_boxed_slice();
  18. let joined: String = boxed.into_iter().collect();
  19. println!("{joined}");
  20. }

輸出:
  1. 寫入 1
  2. 大於 10 的數字:42
  3. xy

同樣的 if let 在 2021 edition 會在執行時 panic:borrow() 的暫存值活到整個 if let ... else 結束,else 裡的 borrow_mut() 因此失敗。scope.rs:
  1. use std::cell::RefCell;
  2. fn main() {
  3. let cell = RefCell::new(None::<i32>);
  4. if let Some(v) = *cell.borrow() {
  5. println!("已有值 {v}");
  6. } else {
  7. *cell.borrow_mut() = Some(1);
  8. println!("寫入 1");
  9. }
  10. println!("{:?}", cell.borrow());
  11. }

rustc --edition 2024 scope.rs && ./scope 的輸出:
  1. 寫入 1
  2. Some(1)

改用 --edition 2021 編譯執行,標準錯誤輸出的前兩行:
  1. thread 'main' (<執行緒 ID>) panicked at scope.rs:8:15:
  2. RefCell already borrowed

升級 edition:cargo fix --edition


用 cargo fix 自動遷移


升級步驟:
  1. 先確認在目前的 edition 下能編譯、測試通過
  2. 執行 cargo fix --edition,Cargo 會把程式碼改成新舊 edition 都能接受的寫法
  3. 把 Cargo.toml 的 edition 改成新值
  4. 重新編譯、跑測試,處理自動修正沒涵蓋到的地方

下面是一個 2021 edition 的專案,用到了沒加 unsafe 的 extern 區塊和名為 gen 的變數,兩者在 2024 都不合法。src/main.rs:
  1. use std::ffi::c_int;
  2. extern "C" {
  3. fn abs(x: c_int) -> c_int;
  4. }
  5. fn main() {
  6. let gen = unsafe { abs(-3) };
  7. println!("gen = {}", gen);
  8. }

在專案目錄執行 cargo fix --edition --allow-no-vcs(--allow-no-vcs 允許在不是 git 儲存庫的目錄中修改;有 git 時建議先 commit,改用預設行為):
  1. Migrating Cargo.toml from 2021 edition to 2024
  2. Checking upgrade v0.1.0 (<專案路徑>)
  3. Migrating src/main.rs from 2021 edition to 2024
  4. Fixed src/main.rs (3 fixes)
  5. Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.09s

<專案路徑> 與耗時會因機器而異。修正後的 src/main.rs:
  1. use std::ffi::c_int;
  2. unsafe extern "C" {
  3. fn abs(x: c_int) -> c_int;
  4. }
  5. fn main() {
  6. let r#gen = unsafe { abs(-3) };
  7. println!("gen = {}", r#gen);
  8. }

再把 Cargo.toml 改成 edition = "2024",cargo run -q 的輸出:
  1. 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 → 編譯測試

資料來源