std::prelude

最後更新


每個 Rust 程式自動匯入的一小組常用名稱,讓你不寫 use 就能用 Vec、Option、String。

這個模組做什麼


寫 Rust 時,你從來沒寫過 use std::vec::Vec; 或 use std::option::Option;,卻能直接用 Vec::new()、Some(1)。原因是編譯器會在每個模組開頭偷偷插入一行:
  1. use std::prelude::rust_2024::*;

前奏(prelude)就像飯店房間裡的「基本備品」:牙刷、毛巾一開始就放好了,不用另外跟櫃台要。標準庫把「幾乎每個程式都會用到」的型別與特徵(trait)放進這份清單,其餘的(例如 HashMap)才需要你自己 use。
情境需要 use 嗎
Vec、String、Box、Option、Result不用,在 prelude 裡
Clone、Copy、Default、Iterator、From/Into不用,在 prelude 裡
HashMap、Rc、fs::File、io::Write要,自己 use
巨集 println!、vec!、format!不用,標準庫巨集本來就全域可用

prelude 只放「名稱」,不會讓程式變大:沒用到的東西不會被編進執行檔。

匯入


prelude 不需要匯入,編譯器自動處理。若想明確寫出來(例如在 #![no_implicit_prelude] 的模組裡),完整路徑是:
  1. use std::prelude::rust_2024::*;

各 edition 對應的模組:std::prelude::v1(2015/2018 共用的基礎)、std::prelude::rust_2015、std::prelude::rust_2018、std::prelude::rust_2021、std::prelude::rust_2024。

常用 API


prelude 裡的型別:Vec、String、Box、Option、Result


這五個是最常用的型別,全部不用 use。Some/None、Ok/Err 這些列舉成員(variant)也一起匯入了,所以可以直接寫 Some(3) 而不是 Option::Some(3)。
完整路徑:
  1. std::vec::Vec
  2. std::string::String
  3. std::boxed::Box
  4. std::option::Option::{self, Some, None}
  5. std::result::Result::{self, Ok, Err}

範例:
  1. fn find_even(v: &Vec<i32>) -> Option<i32> {
  2. v.iter().copied().find(|x| x % 2 == 0)
  3. }
  4. fn parse(s: &str) -> Result<i32, String> {
  5. s.parse::<i32>().map_err(|e| e.to_string())
  6. }
  7. fn main() {
  8. let v: Vec<i32> = vec![1, 3, 4, 7];
  9. let name: String = String::from("rust");
  10. let boxed: Box<i32> = Box::new(42);
  11. println!("{:?}", find_even(&v));
  12. println!("{:?}", parse("12"));
  13. println!("{:?}", parse("x"));
  14. println!("{} {}", name, boxed);
  15. }

輸出:
  1. Some(4)
  2. Ok(12)
  3. Err("invalid digit found in string")
  4. rust 42

prelude 裡的特徵:方法為什麼能直接呼叫


特徵的方法要能呼叫,該特徵必須「在作用域內」。prelude 匯入了一批常用特徵,所以 .clone()、.into()、.to_string()、.iter().map() 都能直接用。
主要成員(Rust 2024 prelude):
類別特徵
複製與預設Clone、Copy、Default
比較PartialEq、Eq、PartialOrd、Ord
轉換From、Into、AsRef、AsMut、TryFrom、TryInto、FromIterator
迭代Iterator、IntoIterator、DoubleEndedIterator、ExactSizeIterator、Extend
字串與記憶體ToString、ToOwned、Drop
閉包與標記Fn、FnMut、FnOnce、Send、Sync、Sized、Unpin
非同步Future、IntoFuture

範例:
  1. #[derive(Debug, Clone, Default, PartialEq)]
  2. struct Point {
  3. x: i32,
  4. y: i32,
  5. }
  6. fn main() {
  7. let p = Point { x: 1, y: 2 };
  8. let q = p.clone();
  9. let origin = Point::default();
  10. let n: i64 = 7i32.into();
  11. let s = 3.5f64.to_string();
  12. let doubled: Vec<i32> = [1, 2, 3].iter().map(|x| x * 2).collect();
  13. println!("{:?} {:?} {}", q, origin, p == q);
  14. println!("{} {} {:?}", n, s, doubled);
  15. }

輸出:
  1. Point { x: 1, y: 2 } Point { x: 0, y: 0 } true
  2. 7 3.5 [2, 4, 6]

不在 prelude 裡的東西要自己 use


HashMap、Rc、io::Write 等不在 prelude 裡,忘記 use 會得到 cannot find type 或「方法不存在」的錯誤。特別是特徵:write! 寫入 String 需要 std::fmt::Write,寫入檔案需要 std::io::Write,兩者都不在 prelude。
範例:
  1. use std::collections::HashMap;
  2. use std::fmt::Write;
  3. use std::rc::Rc;
  4. fn main() {
  5. let mut scores: HashMap<&str, i32> = HashMap::new();
  6. scores.insert("amy", 90);
  7. let shared = Rc::new(String::from("shared"));
  8. let other = Rc::clone(&shared);
  9. let mut out = String::new();
  10. write!(out, "amy={}", scores["amy"]).unwrap();
  11. println!("{} {} {}", out, other, Rc::strong_count(&shared));
  12. }

輸出:
  1. amy=90 shared 2

各 edition 的差異:rust_2021 加入的 TryFrom 與 FromIterator


edition(版次)是 Rust 每隔幾年一次、可選擇升級的語言版本,在 Cargo.toml 的 edition 欄位或 rustc --edition 指定。每個 edition 有自己的 prelude:
模組相較前一版新增
rust_2015/rust_2018與 v1 相同
rust_2021TryFrom、TryInto、FromIterator
rust_2024Future、IntoFuture

所以在 2021 之後,u8::try_from(300) 不用 use std::convert::TryFrom;。
範例:
  1. fn main() {
  2. let ok = u8::try_from(200i32);
  3. let too_big = u8::try_from(300i32);
  4. let small: Result<u8, _> = 100u32.try_into();
  5. let collected = String::from_iter(['h', 'i']);
  6. println!("{:?} {:?} {:?} {}", ok, too_big.is_err(), small, collected);
  7. }

輸出:
  1. Ok(200) true Ok(100) hi

rust_2024 加入的 Future 與 IntoFuture


Rust 2024 起 Future 也在 prelude 裡,寫手動實作 Future 的型別時,不必再 use std::future::Future;。下面的範例自己做一個極簡的執行器(executor):用 std::task::Waker::noop()(Rust 1.85 起)建立什麼都不做的喚醒器,反覆輪詢直到完成。非同步的完整說明見 std::future。
範例:
  1. use std::pin::pin;
  2. use std::task::{Context, Poll, Waker};
  3. async fn add(a: i32, b: i32) -> i32 {
  4. a + b
  5. }
  6. fn block_on<F: Future>(f: F) -> F::Output {
  7. let mut f = pin!(f);
  8. let mut cx = Context::from_waker(Waker::noop());
  9. loop {
  10. if let Poll::Ready(v) = f.as_mut().poll(&mut cx) {
  11. return v;
  12. }
  13. }
  14. }
  15. fn main() {
  16. println!("{}", block_on(add(2, 3)));
  17. }

輸出:
  1. 5

名稱衝突:自己的定義會蓋過 prelude


prelude 的名稱優先順序最低。你在模組裡定義或 use 了同名的東西,就會用你的版本,不會報錯。這讓標準庫可以在新 edition 加名稱而不破壞舊程式,但也代表自訂一個叫 Result 的型別別名會影響整個模組。
注意:若要在遮蔽後仍使用標準版本,寫完整路徑,例如 std::result::Result。
範例:
  1. type Result<T> = std::result::Result<T, String>;
  2. fn half(n: i32) -> Result<i32> {
  3. if n % 2 == 0 { Ok(n / 2) } else { Err(format!("{} 是奇數", n)) }
  4. }
  5. fn main() {
  6. let a: std::result::Result<i32, ()> = Ok(1);
  7. println!("{:?} {:?} {:?}", half(8), half(5), a);
  8. }

輸出:
  1. Ok(4) Err("5 是奇數") Ok(1)

重點整理


  • 編譯器在每個模組自動加上 use std::prelude::rust_20xx::*;,所以 Vec、String、Option、Result、Box 不用匯入
  • prelude 也匯入常用特徵(Clone、Iterator、Into...),它們的方法才能直接呼叫
  • HashMap、Rc、io::Write、fmt::Write 不在 prelude,要自己 use
  • Rust 2021 起加入 TryFrom/TryInto/FromIterator,Rust 2024 起加入 Future/IntoFuture
  • 自己的同名定義會蓋過 prelude,需要時用完整路徑指回標準版本