模組系統

最後更新


用 crate、模組(module)、可見性與路徑,把程式碼分門別類,並決定哪些東西給外面用、哪些藏在裡面。

crate 與模組


程式長到幾百行之後,全部塞在 main.rs 會很難找東西。Rust 用兩層結構來整理:
名詞是什麼比喻
crate一次編譯的單位,產出一個執行檔或一個函式庫一本書
模組(module)crate 裡的命名空間,可以一層層巢狀書裡的章、節
套件(package)一個 Cargo.toml 管理的專案,可含一個函式庫 crate 與多個執行檔 crate一套叢書

crate:binary 與 library


crate 分兩種:有 fn main()、編譯成執行檔的 binary crate,以及給別人引用的 library crate。cargo new 預設建立 binary crate,入口是 src/main.rs;加上 --lib 則建立 library crate,入口是 src/lib.rs。入口檔就是 crate 的「根模組」(crate root),其他模組都掛在它底下。
範例:
  1. $ cargo new shop
  2. $ cargo new --lib recipes

輸出:
  1. Creating binary (application) `shop` package
  2. note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
  3. Creating library `recipes` package
  4. note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

建好的目錄長這樣:
  1. shop/
  2. ├── Cargo.toml
  3. └── src/
  4. └── main.rs
  5. recipes/
  6. ├── Cargo.toml
  7. └── src/
  8. └── lib.rs

更多 Cargo 指令見 Cargo 專案。

mod:在同一個檔案裡分區


mod 名稱 { ... } 定義一個模組,裡面可以放函式、結構、甚至另一個模組。使用時用 :: 串起路徑,像資料夾路徑一樣一層層往下走。
範例(shop/src/main.rs):
  1. mod kitchen {
  2. pub fn cook(dish: &str) -> String {
  3. format!("{} is ready", dish)
  4. }
  5. pub mod storage {
  6. pub fn count() -> u32 {
  7. 3
  8. }
  9. }
  10. }
  11. fn main() {
  12. println!("{}", kitchen::cook("noodles"));
  13. println!("stock: {}", kitchen::storage::count());
  14. }

執行 cargo run,輸出:
  1. Compiling shop v0.1.0 (/path/to/shop)
  2. Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.19s
  3. Running `target/debug/shop`
  4. noodles is ready
  5. stock: 3

Compiling 行括號內實際會印出專案的絕對路徑,這裡改寫成 /path/to/shop;0.19s 是編譯耗時,會因機器而異。之後的範例同樣處理。

可見性


Rust 的模組內容預設是私有(private):只有同一個模組與它的子模組看得到。要讓外面用,就在前面加 pub。這和許多語言「預設公開」的習慣相反,好處是內部細節可以放心修改,不怕別處偷偷依賴。

預設私有:沒加 pub 就呼叫不到


這段無法編譯:secret_sauce 沒有 pub,main 位在 kitchen 模組外面,看不到它。
  1. mod kitchen {
  2. pub fn cook(dish: &str) -> String {
  3. format!("{} is {}", dish, secret_sauce())
  4. }
  5. fn secret_sauce() -> &'static str {
  6. "delicious"
  7. }
  8. }
  9. fn main() {
  10. println!("{}", kitchen::cook("noodles"));
  11. println!("{}", kitchen::secret_sauce());
  12. }

輸出:
  1. error[E0603]: function `secret_sauce` is private
  2. --> src/main.rs:13:29
  3. |
  4. 13 | println!("{}", kitchen::secret_sauce());
  5. | ^^^^^^^^^^^^ private function

cook 和 secret_sauce 在同一個模組,所以 cook 可以呼叫它。刪掉 main 裡的第二行之後就能編譯,輸出 noodles is delicious。

pub struct 的欄位要個別公開


在 struct 前加 pub 只讓型別本身公開,欄位仍然各自預設私有。常見做法是欄位保持私有,透過 pub fn 方法存取,這樣就能保證「餘額只能透過存款改變」這類規則。
這段無法編譯:balance 是私有欄位,模組外不能直接改。
  1. mod bank {
  2. pub struct Account {
  3. pub owner: String,
  4. balance: u64,
  5. }
  6. impl Account {
  7. pub fn new(owner: &str) -> Account {
  8. Account {
  9. owner: owner.to_string(),
  10. balance: 0,
  11. }
  12. }
  13. pub fn deposit(&mut self, amount: u64) {
  14. self.balance += amount;
  15. }
  16. pub fn balance(&self) -> u64 {
  17. self.balance
  18. }
  19. }
  20. }
  21. fn main() {
  22. let mut acc = bank::Account::new("Mia");
  23. acc.deposit(500);
  24. println!("{} has {}", acc.owner, acc.balance());
  25. acc.balance = 1_000_000;
  26. }

輸出:
  1. error[E0616]: field `balance` of struct `Account` is private
  2. --> src/main.rs:29:9
  3. |
  4. 29 | acc.balance = 1_000_000;
  5. | ^^^^^^^ private field

刪掉最後一行後,輸出 Mia has 500。
注意:只要有一個私有欄位,模組外就不能用 Account { ... } 字面值建立它,必須呼叫 new 這類公開的建構函式。enum 則相反,pub enum 的所有變體都自動公開。結構與方法的寫法見 結構 與 方法。

路徑與 use


crate、self、super:從哪裡開始找


路徑有兩種起點:
寫法起點類比
crate::a::bcrate 根模組(絕對路徑)/a/b
self::b目前所在的模組./b
super::b上一層模組../b
a::b目前模組裡名為 a 的項目a/b

範例:
  1. fn shop_name() -> &'static str {
  2. "Rusty Diner"
  3. }
  4. mod front {
  5. pub fn greet() -> String {
  6. format!("Welcome to {}", crate::shop_name())
  7. }
  8. pub mod waiter {
  9. pub fn take_order() -> String {
  10. format!("{} / order: {}", super::greet(), self::menu_item())
  11. }
  12. fn menu_item() -> &'static str {
  13. "fried rice"
  14. }
  15. }
  16. }
  17. fn main() {
  18. println!("{}", crate::front::waiter::take_order());
  19. println!("{}", front::greet());
  20. }

輸出:
  1. Welcome to Rusty Diner / order: fried rice
  2. Welcome to Rusty Diner

shop_name 沒有 pub 也能被 front 使用,因為子模組看得到祖先模組裡的所有項目;可見性只限制「由外往內」看。

use、as 與 pub use


每次都寫完整路徑很累,use 把名稱引入目前的作用域,之後直接用短名稱。幾個常見變化:
  • use a::{self, b}:同時引入模組 a 本身與 a::b
  • use a::B as C:引入後改名,避免撞名
  • pub use:重新匯出(re-export),讓外面可以用較短的路徑取得深層的項目

範例:
  1. mod geometry {
  2. pub mod shapes {
  3. pub fn square(x: f64) -> f64 {
  4. x * x
  5. }
  6. pub fn rect(w: f64, h: f64) -> f64 {
  7. w * h
  8. }
  9. }
  10. pub use self::shapes::square;
  11. }
  12. use geometry::shapes::{self, rect};
  13. use std::collections::BTreeMap as Map;
  14. fn main() {
  15. println!("{}", geometry::square(4.0));
  16. println!("{}", shapes::square(3.0));
  17. println!("{}", rect(2.0, 3.5));
  18. let mut areas = Map::new();
  19. areas.insert("b", 2);
  20. areas.insert("a", 1);
  21. println!("{:?}", areas);
  22. }

輸出:
  1. 16
  2. 9
  3. 7
  4. {"a": 1, "b": 2}

慣例上,函式引入到它所屬的模組(寫 shapes::square(...),一看就知道來源),結構、列舉等型別則直接引入型別名稱(寫 Map::new())。標準庫的路徑與 prelude 自動匯入的項目見 std::prelude。

多檔案模組


mod 名稱; 對應到檔案


把 mod plants { ... } 的大括號換成分號 mod plants;,編譯器就會去檔案裡找模組內容:
宣告位置宣告編譯器找的檔案
src/main.rsmod plants;src/plants.rs 或 src/plants/mod.rs
src/plants.rspub mod tree;src/plants/tree.rs

目錄結構:
  1. garden/
  2. ├── Cargo.toml
  3. └── src/
  4. ├── main.rs
  5. ├── plants.rs
  6. ├── plants/
  7. │ ├── flower.rs
  8. │ └── tree.rs
  9. └── tools.rs

src/main.rs:
  1. mod plants;
  2. mod tools;
  3. fn main() {
  4. let t = plants::tree::Tree::new("oak", 12);
  5. println!("{}", t.describe());
  6. println!("{}", plants::flower::bloom("rose"));
  7. println!("{}", tools::water(t.height));
  8. }

src/plants.rs:
  1. pub mod flower;
  2. pub mod tree;

src/plants/tree.rs:
  1. pub struct Tree {
  2. pub name: String,
  3. pub height: u32,
  4. }
  5. impl Tree {
  6. pub fn new(name: &str, height: u32) -> Tree {
  7. Tree {
  8. name: name.to_string(),
  9. height,
  10. }
  11. }
  12. pub fn describe(&self) -> String {
  13. format!("{} tree, {} m", self.name, self.height)
  14. }
  15. }

src/plants/flower.rs:
  1. pub fn bloom(name: &str) -> String {
  2. format!("{} is blooming", name)
  3. }

src/tools.rs:
  1. pub fn water(height: u32) -> String {
  2. format!("use {} liters of water", height / 2)
  3. }

執行 cargo run,輸出:
  1. Compiling garden v0.1.0 (/path/to/garden)
  2. Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.16s
  3. Running `target/debug/garden`
  4. oak tree, 12 m
  5. rose is blooming
  6. use 6 liters of water

注意:檔案本身不會自動變成模組,一定要有某處寫 mod 名稱; 把它掛進模組樹。反過來,寫了 mod pests; 卻沒有對應檔案,會得到編譯錯誤:
  1. error[E0583]: file not found for module `pests`
  2. --> src/main.rs:1:1
  3. |
  4. 1 | mod pests;
  5. | ^^^^^^^^^^
  6. |
  7. = help: to create the module `pests`, create file "src/pests.rs" or "src/pests/mod.rs"

plants.rs 加 plants/ 目錄是現在建議的寫法;舊專案常見的 plants/mod.rs 效果相同,但編輯器裡會開出一堆同名的 mod.rs 分頁,比較難分辨。

lib.rs 與 main.rs 並存


同一個套件可以同時有 src/lib.rs 與 src/main.rs,它們是兩個獨立的 crate。main.rs 要用函式庫的東西時,路徑開頭寫套件名稱(Cargo.toml 的 name,- 換成 _),就像在用外部套件,只能碰到 pub 的部分。把邏輯放進 lib.rs、main.rs 只負責啟動,是很常見的分工,也方便寫 整合測試。
目錄結構:
  1. temperature/
  2. ├── Cargo.toml
  3. └── src/
  4. ├── lib.rs
  5. └── main.rs

src/lib.rs:
  1. pub mod convert {
  2. pub fn c_to_f(c: f64) -> f64 {
  3. c * 9.0 / 5.0 + 32.0
  4. }
  5. }
  6. pub fn label(c: f64) -> &'static str {
  7. if c >= 30.0 { "hot" } else { "mild" }
  8. }

src/main.rs:
  1. use temperature::convert::c_to_f;
  2. fn main() {
  3. for c in [18.0, 32.5] {
  4. println!("{} C = {} F ({})", c, c_to_f(c), temperature::label(c));
  5. }
  6. }

執行 cargo run,輸出:
  1. Compiling temperature v0.1.0 (/path/to/temperature)
  2. Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.18s
  3. Running `target/debug/temperature`
  4. 18 C = 64.4 F (mild)
  5. 32.5 C = 90.5 F (hot)

重點整理


  • crate 是編譯單位(執行檔或函式庫),模組是 crate 內的命名空間,入口檔 main.rs/lib.rs 是根模組
  • 模組內容預設私有,加 pub 才能從外面使用;pub struct 的欄位要各自加 pub
  • crate:: 從根開始、self:: 從目前模組、super:: 從上一層;子模組看得到祖先的私有項目
  • use 引入短名稱、as 改名、pub use 重新匯出
  • mod 名稱; 會去讀 名稱.rs 或 名稱/mod.rs,沒有宣告的檔案不會被編譯
  • main.rs 透過套件名稱使用 lib.rs,邏輯放函式庫、執行檔保持精簡

資料來源