Rust 從基礎到實踐(10) 模組

rust_logo.jpg
專案要想做到就得有模組化,今天看 Rust 如何進行模組化。定義模組使用 mod
關鍵字來宣告模組,下面定義了 A 、B 和 C 三個模組,B 是巢狀在 A 中,這些模組中都提供了 a 和 b 方法。
mod A{ fn a(){} fn b(){} mod B { fn a(){} fn b(){} } } mod C{ fn a(){} fn b(){} }
fn main(){ A::b(); }
這樣呼叫模組 A 中 b 方法,編譯時候提示 b 是一個私有函式。
mod A{ pub fn a(){} pub fn b(){} mod B { fn a(){} fn b(){} } }
我們需要在 b 前面新增 pub 表示在模組 A 外通過 A::b() 是可以呼叫到這個方法的。
fn main(){ A::b(); A::B::a() }
因為模組 B 在模組 A 中我們也需要將其定義為 pub 這樣外面才能呼叫到。
error[E0603]: module `B` is private --> src/main.rs:17:8 | 17 |A::B::a() |
這樣修改後我們 main 中就可以訪問到 A::B::b() 方法了。
mod A{ pub fn a(){} pub fn b(){} pub mod B { pub fn a(){} pub fn b(){} } }
現在我們雖然通過模組對專案進行劃分為 A B 和 C 模組。但是在實際開發過程中我們是不能將所有模組都寫入一個檔案。

螢幕快照 2019-04-06 上午9.27.26.png
我們需要通過檔案和目錄的形式來管理我們的專案模組節點
- 定義資料夾 A 作為 A 模組
- 外層定義 C.rs 做 C 模組
下面我們分別看看這些檔案中包含哪些具體的內容
B.rs
pub fn a(){} pub fn b(){}
A/mod.rs
這裡值得注意我們在 A 資料夾(相當於定義模組A)需要定義 mod.rs 作為模組 A 的入口檔案。這裡定義名稱是有要求的,需要定義為 mod.rs。
pub mod B; pub fn a(){} pub fn b(){}
C.rs
pub fn a(){} pub fn b(){}
main.rs
fn main(){ A::b(); A::B::a(); }

americancaptain3_20160428193042_09.jpg
pub mod a { pub mod b{ pub mod c{ pub mod d{ pub fn e(){ } } } } } fn main(){ a::b::c::d::e(); }
這樣層層巢狀,實在是麻煩。當然有簡便方法
use a::b::c::d; fn main(){ d::e(); }
列舉也是有名稱空間,同樣可以 use 定義來節省寫程式碼的量。
enum Ex { A, B, C, } use Ex::{A,C}; fn main(){ d::e(); A }
這裡同樣支援萬用字元
use Ex::*

th.jpeg