1. 為什麼需要模組
隨著程式越寫越大,全部放在一個檔案會變得混亂。Rust 提供 module system(模組系統),讓程式可以分成多個檔案或區塊,方便管理與重用。
2. 基本模組宣告
用 mod 宣告模組,模組裡面可以有函數、結構體等。
mod greetings {
pub fn hello() {
println!("Hello from module!");
}
}
fn main() {
greetings::hello();
}
輸出:
Hello from module!
這裡要特別注意 pub,如果不加的話,模組裡的函數預設是私有的,無法在外部呼叫。
3. 巢狀模組
模組可以巢狀。
mod outer {
pub mod inner {
pub fn say_hi() {
println!("Hi from inner module!");
}
}
}
fn main() {
outer::inner::say_hi();
}
輸出:
Hi from inner module!
從 crate 根開始也可以寫成:
crate::outer::inner::say_hi();
相對於目前模組則能用 self::,往上一層則是 super::。
4. use 簡化路徑
每次都寫完整路徑會很長,可以用 use 簡化。
mod math {
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
}
use math::add;
fn main() {
println!("1 + 2 = {}", add(1, 2));
}
輸出:
1 + 2 = 3
use 只會把指定名稱引入當前作用域,不會像 C++ 的 using namespace 那樣把所有名稱攤平,因此衝突更好控管。
5. 檔案與模組
以 binary 專案為例,檔案通常放在 src/:
mod greetings;
fn main() {
greetings::hello();
}
src/greetings.rs 內容:
pub fn hello() {
println!("Hello from another file!");
}
輸出:
Hello from another file!
6. 學習心得與補充
今天學到模組系統,之前學到的 struct、enum 可以幫我組織資料,而模組則是幫我組織程式碼。特別是 pub 的設計,讓我想到 C++ 的 public/private 權限控制,但在 Rust 中更直觀,不小心就會被提醒權限問題。用 use 簡化路徑的時候,我覺得雖然有點像 C++ 的 using,但 use 是顯式引入,不會把一整個命名空間灑進來,因此不容易發生命名衝突。再加上 crate::、self::、super:: 這些路徑工具,整個模組系統既靈活又清楚。一步一步學下來,我發現 Rust 不只是語法新鮮,而是整個在安全和清楚結構上都有很強的設計理念