模組系統
最後更新
用 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),其他模組都掛在它底下。範例:
- $ cargo new shop
- $ cargo new --lib recipes
輸出:
- Creating binary (application) `shop` package
- note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
- Creating library `recipes` package
- note: see more `Cargo.toml` keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
建好的目錄長這樣:
- shop/
- ├── Cargo.toml
- └── src/
- └── main.rs
- recipes/
- ├── Cargo.toml
- └── src/
- └── lib.rs
更多 Cargo 指令見 Cargo 專案。
mod:在同一個檔案裡分區
mod 名稱 { ... } 定義一個模組,裡面可以放函式、結構、甚至另一個模組。使用時用 :: 串起路徑,像資料夾路徑一樣一層層往下走。範例(
shop/src/main.rs):- mod kitchen {
- pub fn cook(dish: &str) -> String {
- format!("{} is ready", dish)
- }
- pub mod storage {
- pub fn count() -> u32 {
- 3
- }
- }
- }
- fn main() {
- println!("{}", kitchen::cook("noodles"));
- println!("stock: {}", kitchen::storage::count());
- }
執行
cargo run,輸出:- Compiling shop v0.1.0 (/path/to/shop)
- Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.19s
- Running `target/debug/shop`
- noodles is ready
- stock: 3
Compiling 行括號內實際會印出專案的絕對路徑,這裡改寫成 /path/to/shop;0.19s 是編譯耗時,會因機器而異。之後的範例同樣處理。可見性
Rust 的模組內容預設是私有(private):只有同一個模組與它的子模組看得到。要讓外面用,就在前面加
pub。這和許多語言「預設公開」的習慣相反,好處是內部細節可以放心修改,不怕別處偷偷依賴。預設私有:沒加 pub 就呼叫不到
這段無法編譯:
secret_sauce 沒有 pub,main 位在 kitchen 模組外面,看不到它。- mod kitchen {
- pub fn cook(dish: &str) -> String {
- format!("{} is {}", dish, secret_sauce())
- }
- fn secret_sauce() -> &'static str {
- "delicious"
- }
- }
- fn main() {
- println!("{}", kitchen::cook("noodles"));
- println!("{}", kitchen::secret_sauce());
- }
輸出:
- error[E0603]: function `secret_sauce` is private
- --> src/main.rs:13:29
- |
- 13 | println!("{}", kitchen::secret_sauce());
- | ^^^^^^^^^^^^ private function
cook 和 secret_sauce 在同一個模組,所以 cook 可以呼叫它。刪掉 main 裡的第二行之後就能編譯,輸出 noodles is delicious。pub struct 的欄位要個別公開
在
struct 前加 pub 只讓型別本身公開,欄位仍然各自預設私有。常見做法是欄位保持私有,透過 pub fn 方法存取,這樣就能保證「餘額只能透過存款改變」這類規則。這段無法編譯:
balance 是私有欄位,模組外不能直接改。- mod bank {
- pub struct Account {
- pub owner: String,
- balance: u64,
- }
- impl Account {
- pub fn new(owner: &str) -> Account {
- Account {
- owner: owner.to_string(),
- balance: 0,
- }
- }
- pub fn deposit(&mut self, amount: u64) {
- self.balance += amount;
- }
- pub fn balance(&self) -> u64 {
- self.balance
- }
- }
- }
- fn main() {
- let mut acc = bank::Account::new("Mia");
- acc.deposit(500);
- println!("{} has {}", acc.owner, acc.balance());
- acc.balance = 1_000_000;
- }
輸出:
- error[E0616]: field `balance` of struct `Account` is private
- --> src/main.rs:29:9
- |
- 29 | acc.balance = 1_000_000;
- | ^^^^^^^ private field
刪掉最後一行後,輸出
Mia has 500。注意:只要有一個私有欄位,模組外就不能用
Account { ... } 字面值建立它,必須呼叫 new 這類公開的建構函式。enum 則相反,pub enum 的所有變體都自動公開。結構與方法的寫法見 結構 與 方法。路徑與 use
crate、self、super:從哪裡開始找
路徑有兩種起點:
| 寫法 | 起點 | 類比 |
|---|---|---|
crate::a::b | crate 根模組(絕對路徑) | /a/b |
self::b | 目前所在的模組 | ./b |
super::b | 上一層模組 | ../b |
a::b | 目前模組裡名為 a 的項目 | a/b |
範例:
- fn shop_name() -> &'static str {
- "Rusty Diner"
- }
- mod front {
- pub fn greet() -> String {
- format!("Welcome to {}", crate::shop_name())
- }
- pub mod waiter {
- pub fn take_order() -> String {
- format!("{} / order: {}", super::greet(), self::menu_item())
- }
- fn menu_item() -> &'static str {
- "fried rice"
- }
- }
- }
- fn main() {
- println!("{}", crate::front::waiter::take_order());
- println!("{}", front::greet());
- }
輸出:
- Welcome to Rusty Diner / order: fried rice
- Welcome to Rusty Diner
shop_name 沒有 pub 也能被 front 使用,因為子模組看得到祖先模組裡的所有項目;可見性只限制「由外往內」看。use、as 與 pub use
每次都寫完整路徑很累,
use 把名稱引入目前的作用域,之後直接用短名稱。幾個常見變化:use a::{self, b}:同時引入模組a本身與a::buse a::B as C:引入後改名,避免撞名pub use:重新匯出(re-export),讓外面可以用較短的路徑取得深層的項目
範例:
- mod geometry {
- pub mod shapes {
- pub fn square(x: f64) -> f64 {
- x * x
- }
- pub fn rect(w: f64, h: f64) -> f64 {
- w * h
- }
- }
- pub use self::shapes::square;
- }
- use geometry::shapes::{self, rect};
- use std::collections::BTreeMap as Map;
- fn main() {
- println!("{}", geometry::square(4.0));
- println!("{}", shapes::square(3.0));
- println!("{}", rect(2.0, 3.5));
- let mut areas = Map::new();
- areas.insert("b", 2);
- areas.insert("a", 1);
- println!("{:?}", areas);
- }
輸出:
- 16
- 9
- 7
- {"a": 1, "b": 2}
慣例上,函式引入到它所屬的模組(寫
shapes::square(...),一看就知道來源),結構、列舉等型別則直接引入型別名稱(寫 Map::new())。標準庫的路徑與 prelude 自動匯入的項目見 std::prelude。多檔案模組
mod 名稱; 對應到檔案
把
mod plants { ... } 的大括號換成分號 mod plants;,編譯器就會去檔案裡找模組內容:| 宣告位置 | 宣告 | 編譯器找的檔案 |
|---|---|---|
src/main.rs | mod plants; | src/plants.rs 或 src/plants/mod.rs |
src/plants.rs | pub mod tree; | src/plants/tree.rs |
目錄結構:
- garden/
- ├── Cargo.toml
- └── src/
- ├── main.rs
- ├── plants.rs
- ├── plants/
- │ ├── flower.rs
- │ └── tree.rs
- └── tools.rs
src/main.rs:- mod plants;
- mod tools;
- fn main() {
- let t = plants::tree::Tree::new("oak", 12);
- println!("{}", t.describe());
- println!("{}", plants::flower::bloom("rose"));
- println!("{}", tools::water(t.height));
- }
src/plants.rs:- pub mod flower;
- pub mod tree;
src/plants/tree.rs:- pub struct Tree {
- pub name: String,
- pub height: u32,
- }
- impl Tree {
- pub fn new(name: &str, height: u32) -> Tree {
- Tree {
- name: name.to_string(),
- height,
- }
- }
- pub fn describe(&self) -> String {
- format!("{} tree, {} m", self.name, self.height)
- }
- }
src/plants/flower.rs:- pub fn bloom(name: &str) -> String {
- format!("{} is blooming", name)
- }
src/tools.rs:- pub fn water(height: u32) -> String {
- format!("use {} liters of water", height / 2)
- }
執行
cargo run,輸出:- Compiling garden v0.1.0 (/path/to/garden)
- Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.16s
- Running `target/debug/garden`
- oak tree, 12 m
- rose is blooming
- use 6 liters of water
注意:檔案本身不會自動變成模組,一定要有某處寫
mod 名稱; 把它掛進模組樹。反過來,寫了 mod pests; 卻沒有對應檔案,會得到編譯錯誤:- error[E0583]: file not found for module `pests`
- --> src/main.rs:1:1
- |
- 1 | mod pests;
- | ^^^^^^^^^^
- |
- = 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 只負責啟動,是很常見的分工,也方便寫 整合測試。目錄結構:
- temperature/
- ├── Cargo.toml
- └── src/
- ├── lib.rs
- └── main.rs
src/lib.rs:- pub mod convert {
- pub fn c_to_f(c: f64) -> f64 {
- c * 9.0 / 5.0 + 32.0
- }
- }
- pub fn label(c: f64) -> &'static str {
- if c >= 30.0 { "hot" } else { "mild" }
- }
src/main.rs:- use temperature::convert::c_to_f;
- fn main() {
- for c in [18.0, 32.5] {
- println!("{} C = {} F ({})", c, c_to_f(c), temperature::label(c));
- }
- }
執行
cargo run,輸出:- Compiling temperature v0.1.0 (/path/to/temperature)
- Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.18s
- Running `target/debug/temperature`
- 18 C = 64.4 F (mild)
- 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,邏輯放函式庫、執行檔保持精簡