mod 声明模块。pub 控制可见性。
随着项目变大,把所有代码放在 main.rs 或 lib.rs 中会变得难以维护。Rust 提供了模块系统来组织代码:
mod front_of_house { mod hosting { fn add_to_waitlist() {} fn seat_at_table() {} } mod serving { fn take_order() {} fn serve_order() {} fn take_payment() {} } }
这里 front_of_house 是模块,hosting 和 serving 是它的子模块。
如果把 crate 看作一棵树,根模块 crate 就是树根:
crate
└── front_of_house
├── hosting
│ ├── add_to_waitlist
│ └── seat_at_table
└── serving
├── take_order
├── serve_order
└── take_payment
访问模块中的项需要指定路径。路径有两种:
crate 开始,例如 crate::front_of_house::hosting::add_to_waitlist。front_of_house::hosting::add_to_waitlist。pub fn eat_at_restaurant() { // 绝对路径 crate::front_of_house::hosting::add_to_waitlist(); // 相对路径 front_of_house::hosting::add_to_waitlist(); }
默认情况下,模块内的项对父模块是私有的。需要对外暴露时加上 pub:
mod front_of_house { pub mod hosting { pub fn add_to_waitlist() {} } } pub fn eat_at_restaurant() { crate::front_of_house::hosting::add_to_waitlist(); }
注意:父模块中的项无法访问子模块中的私有项,但子模块可以访问祖先模块中的项。
模块不仅可以内联定义,还可以放到单独文件中:
src ├── main.rs └── front_of_house.rs
在 main.rs 中:
mod front_of_house; pub fn eat_at_restaurant() { front_of_house::hosting::add_to_waitlist(); }
在 front_of_house.rs 中:
pub mod hosting; pub fn add_to_waitlist() {}
更复杂的模块还可以放到目录中:
src
├── main.rs
└── front_of_house
├── mod.rs
└── hosting.rs
从 Rust 2018 起,更推荐使用 `front_of_house.rs` 与 `front_of_house/` 目录并存的结构,而非必须写 `mod.rs`。
## 19.7 小结
| 关键字 | 作用 |
mod | 声明或引用模块 |
pub | 使项对外可见 |
crate:: | 绝对路径,从根模块开始 |
| 相对路径 | 从当前模块开始 |
pub mod hosting 和 pub fn add_to_waitlist 都需要加 pub?