# 模組系統

用 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），其他模組都掛在它底下。

範例：

```text
$ cargo new shop
$ cargo new --lib recipes
```

輸出：

```text
    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
```

建好的目錄長這樣：

```text
shop/
├── Cargo.toml
└── src/
    └── main.rs
recipes/
├── Cargo.toml
└── src/
    └── lib.rs
```

更多 Cargo 指令見 [Cargo 專案](/start-cargo)。

### mod：在同一個檔案裡分區

`mod 名稱 { ... }` 定義一個模組，裡面可以放函式、結構、甚至另一個模組。使用時用 `::` 串起路徑，像資料夾路徑一樣一層層往下走。

範例（`shop/src/main.rs`）：

```rust
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`，輸出：

```text
   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` 模組外面，看不到它。

```rust
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());
}
```

輸出：

```text
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` 是私有欄位，模組外不能直接改。

```rust
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;
}
```

輸出：

```text
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` 的所有變體都自動公開。結構與方法的寫法見 [結構](/structs-basics) 與 [方法](/structs-methods)。

## 路徑與 use

### crate、self、super：從哪裡開始找

路徑有兩種起點：

| 寫法 | 起點 | 類比 |
| --- | --- | --- |
| `crate::a::b` | crate 根模組（絕對路徑） | `/a/b` |
| `self::b` | 目前所在的模組 | `./b` |
| `super::b` | 上一層模組 | `../b` |
| `a::b` | 目前模組裡名為 `a` 的項目 | `a/b` |

範例：

```rust
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());
}
```

輸出：

```text
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::b`
- `use a::B as C`：引入後改名，避免撞名
- `pub use`：重新匯出（re-export），讓外面可以用較短的路徑取得深層的項目

範例：

```rust
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);
}
```

輸出：

```text
16
9
7
{"a": 1, "b": 2}
```

慣例上，函式引入到它所屬的模組（寫 `shapes::square(...)`，一看就知道來源），結構、列舉等型別則直接引入型別名稱（寫 `Map::new()`）。標準庫的路徑與 prelude 自動匯入的項目見 [std::prelude](/pkg-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` |

目錄結構：

```text
garden/
├── Cargo.toml
└── src/
    ├── main.rs
    ├── plants.rs
    ├── plants/
    │   ├── flower.rs
    │   └── tree.rs
    └── tools.rs
```

`src/main.rs`：

```rust
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`：

```rust
pub mod flower;
pub mod tree;
```

`src/plants/tree.rs`：

```rust
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`：

```rust
pub fn bloom(name: &str) -> String {
    format!("{} is blooming", name)
}
```

`src/tools.rs`：

```rust
pub fn water(height: u32) -> String {
    format!("use {} liters of water", height / 2)
}
```

執行 `cargo run`，輸出：

```text
   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;` 卻沒有對應檔案，會得到編譯錯誤：

```text
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` 只負責啟動，是很常見的分工，也方便寫 [整合測試](/testing-integration)。

目錄結構：

```text
temperature/
├── Cargo.toml
└── src/
    ├── lib.rs
    └── main.rs
```

`src/lib.rs`：

```rust
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`：

```rust
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`，輸出：

```text
   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`，邏輯放函式庫、執行檔保持精簡

## 資料來源

- [The Rust Programming Language（章節架構參考）](https://doc.rust-lang.org/book/)
- [The Rust Reference](https://doc.rust-lang.org/reference/)
- [Rust 標準庫文件](https://doc.rust-lang.org/std/)
- [Rust 官方部落格](https://blog.rust-lang.org/)
